Search code examples
iosswiftuitokenize

Implement tokens in a SwiftUI TextField


How can I make TextField in SwiftUI have tokens like an UISearchBar?

I've tried to insert an UISearchBar so I could use them, but I lost the behavior from the interaction between the TextField and the List.


Solution

  • In iOS 16, Apple have added SwiftUI support for this to searchable view modifiers, e.g. searchable(text:tokens:placement:prompt:token:) (API docs)

    Example from the docs

    enum FruitToken: Identifiable, Hashable, CaseIterable {
        case apple
        case pear
        case banana
        var id: Self { self }
    }
    
    @State private var tokens: [FruitToken] = []
    
    ProductList()
        .searchable(text: $text, tokens: $tokens) { token in
            switch token {
            case .apple: Text("Apple")
            case .pear: Text("Pear")
            case .banana: Text("Banana")
            }
        }