iosswiftswiftui

SwiftUI TextField max length


Is it possible to set a maximum length for TextField? I was thinking of handling it using onEditingChanged event but it is only called when the user begins/finishes editing and not called while user is typing. I've also read the docs but haven't found anything yet. Is there any workaround?

TextField($text, placeholder: Text("Username"), onEditingChanged: { _ in
  print(self.$text)
}) {
  print("Finished editing")
}

Solution

  • You can do it with Combine in a simple way.

    Like so:

    import SwiftUI
    import Combine
    
    struct ContentView: View {
    
        @State var username = ""
    
        let textLimit = 10 //Your limit
        
        var body: some View {
            //Your TextField
            TextField("Username", text: $username)
            .onReceive(Just(username)) { _ in limitText(textLimit) }
        }
    
        //Function to keep text length in limits
        func limitText(_ upper: Int) {
            if username.count > upper {
                username = String(username.prefix(upper))
            }
        }
    }