SwiftUI TextField max length

后端 未结 6 931
伪装坚强ぢ
伪装坚强ぢ 2020-11-30 06:52

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 us

6条回答
  •  [愿得一人]
    2020-11-30 06:55

    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))
            }
        }
    }
    

提交回复
热议问题