How can I use Combine to track UITextField changes in a UIViewRepresentable class?

前端 未结 3 2034
说谎
说谎 2020-12-15 14:37

I have created a custom text field and I\'d like to take advantage of Combine. In order to be notified whenever text changes in my text field, I currently use a custom modif

3条回答
  •  清酒与你
    2020-12-15 14:59

    I'm a little confused with what you're asking because you're talking about UITextField and SwiftUI.

    What about something like this? It doesn't use UITextField instead it uses SwiftUI's TextField object instead.

    This class will notify you whenever there's a change to the TextField in your ContentView.

    class CustomModifier: ObservableObject {
        var observedValue: String = "" {
            willSet(observedValue) {
                print(observedValue)
            }
        }
    }
    

    Ensure that you use @ObservedObject on your modifier class and you'll be able to see the changes.

    struct ContentView: View {
        @ObservedObject var modifier = CustomModifier()
    
        var body: some View {
            TextField("Input:", text: $modifier.observedValue)
        }
    }
    

    If this is completely off track with what you're asking then can I suggest the following article, which may help?

    https://medium.com/@valv0/textfield-and-uiviewrepresentable-46a8d3ec48e2

提交回复
热议问题