UITextField text change event

后端 未结 21 1287
南方客
南方客 2020-11-22 06:49

How can I detect any text changes in a textField? The delegate method shouldChangeCharactersInRange works for something, but it did not fulfill my need exactly.

21条回答
  •  一整个雨季
    2020-11-22 07:47

    SwiftUI

    If you are using the native SwiftUI TextField or just using the UIKit UITextField (here is how), you can observe for text changes like:

    SwiftUI 2.0

    From iOS 14, macOS 11, or any other OS contains SwiftUI 2.0, there is a new modifier called .onChange that detects any change of the given state:

    struct ContentView: View {
        @State var text: String = ""
    
        var body: some View {
            TextField("Enter text here", text: $text)
                .onChange(of: text) {
                    print($0) // You can do anything due to the change here.
                    // self.autocomplete($0) // like this
                }
        }
    }
    

    SwiftUI 1.0

    For older iOS and other SwiftUI 1.0 platforms, you can use onReceive with the help of the combine framework:

    import Combine
    
    .onReceive(Just(text)) { 
        print($0)
    }
    

    Note that you can use text.publisher instead of Just(text) but it returns the change instead of the entire value.

提交回复
热议问题