Limit characters in a Form using @Binding - SwiftUI

Sep 16, 2021 1 min read
Limit characters in a Form using @Binding - SwiftUI

We can accomplish the task by using a Binding extension like so:

extension Binding where Value == String {
    func max(_ limit: Int) -> Self {
        if self.wrappedValue.count > limit {
            DispatchQueue.main.async {
                self.wrappedValue = String(self.wrappedValue.dropLast())
            }
        }
        return self
    }
}

and this is how you would use it:

struct DemoView: View {
    @State private var textField = ""
    var body: some View {
        TextField("8 Char Limit", text: self.$textField.max(8)) // Here
            .padding()
    }
}

This is extremely useful for validating a user form.

Sources: 1

With love and respect,
Arturo 👨🏻‍💻

Great! Next, complete checkout for full access to ArturoFM.
Welcome back! You've successfully signed in.
You've successfully subscribed to ArturoFM.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.