SwiftUI TextField max length

A slightly shorter version of Paulw11’s answer would be:

class TextBindingManager: ObservableObject {
    @Published var text = "" {
        didSet {
            if text.count > characterLimit && oldValue.count <= characterLimit {
                text = oldValue
            }
        }
    }
    let characterLimit: Int

    init(limit: Int = 5){
        characterLimit = limit
    }
}

struct ContentView: View {
    @ObservedObject var textBindingManager = TextBindingManager(limit: 5)
    
    var body: some View {
        TextField("Placeholder", text: $textBindingManager.text)
    }
}

All you need is an ObservableObject wrapper for the TextField string. Think of it as an interpreter that gets notified every time there’s a change and is able to send modifications back to the TextField. However, there’s no need to create the PassthroughSubject, using the @Published modifier will have the same result, in less code.

One mention, you need to use didSet, and not willSet or you can end up in a recursive loop.

Leave a Comment