Tags

Personal Catalogue: iOS (Swift & SwiftUI)

Course 1 ยท Chapter 7 ยท Tag Editor, Suggestions and Chips

Items can have tags in the database, but the form can only preserve the ones they already have. This chapter adds a tag editor to the form: type a tag and press return to add it, see suggestions drawn from tags you already use, and remove a tag with one tap. The rules from the shared spec are the point: "Web Development" and "web development" are the same tag, and a tag can never appear twice on one item.

What was run, and what was not
Nothing in this chapter was compiled or run (no Mac or Xcode here). My search was about wrapping chip layouts only: it found several tutorials building one with SwiftUI's Layout protocol, plus ready-made packages, so the approach is real. It found nothing on SwiftData tag relationships or on suggestion-as-you-type fields; those parts, and every API detail, are from my memory and are the likeliest place for compile errors.

Where the Work Happens

JobAndroid (Chapter 7)iOS (this chapter)
Case-insensitive identityRoom NOCASE unique index (ASCII only)A folded key property, unique (Chapter 2)
Find or createRepository transactionCatalogueRepository.tag(named:) (Chapter 3)
Join rowsExplicit cross-reference rowsAssigning item.tags; SwiftData writes the join
Wrapping chipsFlowRowA small custom Layout (no built-in wrapping stack)
SuggestionsFiltered list under the fieldFiltered list under the field

Almost everything database-side already exists. The draft from Chapter 6 carries tagNames, and CatalogueRepository.save(_:tagNames:) already finds or creates a Tag for each name, by its folded key, and assigns them to the item. So the many-to-many write needs no new code; this chapter is about the screen that edits the names.

Step 1: A Wrapping Layout

A HStack never wraps, and a row of tags needs to. The tutorials in my search build a flow layout by conforming to the Layout protocol and implementing two methods: one to report the size, one to place the children. This version is deliberately small; if you would rather not maintain it, the packages in the sources do the same job.

import SwiftUI struct FlowLayout: Layout { var spacing: CGFloat = 8 func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { let maxWidth = proposal.width ?? .infinity var x: CGFloat = 0, y: CGFloat = 0, rowHeight: CGFloat = 0, widest: CGFloat = 0 for view in subviews { let size = view.sizeThatFits(.unspecified) if x > 0 && x + size.width > maxWidth { x = 0; y += rowHeight + spacing; rowHeight = 0 } x += size.width + spacing rowHeight = max(rowHeight, size.height) widest = max(widest, x - spacing) } return CGSize(width: widest, height: y + rowHeight) } func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { var x = bounds.minX, y = bounds.minY, rowHeight: CGFloat = 0 for view in subviews { let size = view.sizeThatFits(.unspecified) if x > bounds.minX && x + size.width > bounds.maxX { x = bounds.minX; y += rowHeight + spacing; rowHeight = 0 } view.place(at: CGPoint(x: x, y: y), proposal: .unspecified) x += size.width + spacing rowHeight = max(rowHeight, size.height) } } }

The idea: lay children left to right; when the next one would pass the right edge, start a new row. sizeThatFits does a dry run to report the total height, and placeSubviews does it again for real.

Step 2: The Tag Editor

TagEditor edits a Binding<[String]> (the draft's tagNames), so it knows nothing about SwiftData writes. It reads the existing tags with @Query only to offer suggestions. Adding goes through the same folding as storage, so the duplicate rule is enforced in one way everywhere.

import SwiftUI import SwiftData struct TagEditor: View { @Binding var tagNames: [String] @Query(sort: \Tag.name) private var allTags: [Tag] @State private var input = "" // Existing tags matching what is typed, not already on this item. private var suggestions: [String] { let typed = Tag.key(for: input) guard !typed.isEmpty else { return [] } let chosen = Set(tagNames.map(Tag.key(for:))) return allTags .filter { $0.key.contains(typed) && !chosen.contains($0.key) } .prefix(5) .map(\.name) } var body: some View { VStack(alignment: .leading, spacing: 10) { if !tagNames.isEmpty { FlowLayout { ForEach(tagNames, id: \.self) { name in TagChip(name: name) { remove(name) } } } } TextField("Add a tag", text: $input) .textInputAutocapitalization(.never) .submitLabel(.done) .onSubmit { add(input) } if !suggestions.isEmpty { FlowLayout { ForEach(suggestions, id: \.self) { name in Button(name) { add(name) } .buttonStyle(.bordered) .controlSize(.small) } } } } } private func add(_ raw: String) { let name = Tag.cleaned(raw) defer { input = "" } guard !name.isEmpty else { return } let key = Tag.key(for: name) if tagNames.contains(where: { Tag.key(for: $0) == key }) { return } // already on this item // Reuse the stored spelling if the tag exists, so "swift" adds the existing "Swift". let stored = allTags.first(where: { $0.key == key })?.name tagNames.append(stored ?? name) } private func remove(_ name: String) { tagNames.removeAll { $0 == name } } } struct TagChip: View { let name: String let onRemove: () -> Void var body: some View { HStack(spacing: 4) { Text(name) Button(action: onRemove) { Image(systemName: "xmark.circle.fill") } .buttonStyle(.plain) .accessibilityLabel("Remove tag \(name)") } .font(.subheadline) .padding(.horizontal, 10) .padding(.vertical, 5) .background(.tint.opacity(0.15), in: Capsule()) } }

I assumed Tag.cleaned(_:) (trim and collapse spaces) and Tag.key(for:) (fold case and diacritics) keep the static signatures from Chapter 2; if yours differ, adjust the calls, not the logic. Three details matter. Duplicates are decided by the key, so adding "SWIFT" to an item that already has "Swift" does nothing. The stored spelling wins: typing "swift" when "Swift" exists adds "Swift", so the catalogue does not drift into several spellings. And suggestions never offer what is already chosen.

Step 3: Put It in the Form

In ItemFormView, add a section between the year and the notes. The editor changes draft.tagNames, the same array save() already hands to the repository, so there is nothing else to change.

Section("Tags") { TagEditor(tagNames: $draft.tagNames) }

One problem to watch for: if the user types a tag and taps Save without pressing return, the text in the field is lost. That is a real usability trap. Exercise 2 asks you to fix it. Also, ItemRow and DetailView already show sortedTags, so tags appear there with no further work.

Tags nobody uses. Remove the last item carrying a tag and the Tag stays in the store (the delete rules from Chapter 2 clear only the link). That is harmless for now, and it even keeps the tag as a suggestion. Chapter 8's filter row should show only tags in use; clean-up of orphans is left as a decision for you, in Exercise 3.

Compare with the Android course
Personal Catalogue: Android (Kotlin & Compose) Chapter 7 needed an explicit cross-reference table and a transaction to keep the join rows consistent, and an ASCII-only NOCASE index forced a separate normalised column anyway. On iOS the folded key from Chapter 2 does the same job, and assigning item.tags is the whole many-to-many write. The cost: the unique-key behaviour of SwiftData on a duplicate insert is one of the unverified points in this course, which is why the repository finds before it inserts. The wrapping chips are the reverse: Compose gives you FlowRow, SwiftUI makes you write the layout.

Challenges

Exercise 1

Add FlowLayout, TagEditor and TagChip and the form section. Add the tags "Sci-Fi", "sci-fi" and "SCI-FI" to one item in turn, then open another item and type "sci". Write down what each did and what the suggestion list showed.

๐Ÿ“„ View solution
Exercise 2

Fix the lost-text trap: if the tag field holds text when Save is pressed, that text should be added as a tag. Decide whether the fix belongs in TagEditor, in ItemFormView or in ItemDraft, and explain what makes the other places awkward.

๐Ÿ“„ View solution
Exercise 3

Decide what should happen to a tag no item uses any more. Give the arguments for keeping it and for deleting it, choose one, and write the code that implements your choice (where would it run, and what must it check?).

๐Ÿ“„ View solution

Chapter 7 Quick Reference

  • The editor edits Binding<[String]>; the repository's find-or-create (Chapter 3) does the many-to-many write, so the screen needs no database code
  • Duplicates are decided by the folded key; reuse the stored spelling of an existing tag
  • No built-in wrapping stack: conform to Layout (sizeThatFits + placeSubviews) or use a package
  • Return key: .submitLabel(.done) + .onSubmit { }
  • Suggestions: filter @Query tags by the typed key, exclude chosen ones, cap the list
  • Unused tags stay in the store unless you remove them deliberately
Not Yet Verified
Checked (one web search on 2026-11-19): that SwiftUI has no wrapping stack and that tag-chip layouts are commonly built by conforming to the Layout protocol, with ready-made packages (Flow and swiftui-flow-layout) available; one tutorial also touches on tag uniqueness checks, which I did not read.
Not checked, from general knowledge: the exact Layout method signatures and the Void cache type used above (the likeliest compile error here); ProposedViewSize handling of .infinity; .onSubmit on a TextField inside a Form section; .submitLabel; .tint.opacity(_:) as a shape style; .buttonStyle(.bordered) with .controlSize(.small); that assigning item.tags writes the join without further code; the SwiftData unique-key behaviour (still unverified, as in Chapter 3); and all code, none of which was compiled. I did not consult Apple's reference pages.
Coming next
Personal Catalogue: iOS (Swift & SwiftUI) 8 adds search and filtering: a search field, a tag filter, and the "do I own this?" check, where the dynamic @Query pattern from Chapter 4's discussion is finally used.