How do you get a signal every time a UITextField text property changes in RxSwift

Viewed 17205

How do you get a signal from programmatically made changes to UITextField text property? By using rx.text only reports a signal when the user input the text by keyboard. If you set textField.text programmatically, the signal doesn't fire.

This is how I'm using rx.text

(self.phoneNumberTextField.rx.text).orEmpty.subscribe(onNext: { [weak self] (phone) in
         // do something
    }).addDisposableTo(disposeBag)
    self.phoneNumberTextField.text = "this is for test"

Thank you!

4 Answers

I had the same issues, apparently sweeper's answer did not work for me. So here is what I did When I set the text for textfield manually, I call sendActions method on the text field

textField.text = "Programmatically set text." textField.sendActions(for: .valueChanged)

On digging a little bit more, I realized that the rx.text depends on UIControlEvents and these are not triggered when you explicitly set the text.

Hope this helps

You can add controlEvents to asObservable:

    textField.rx.controlEvent([.editingChanged])
        .asObservable().subscribe({ [unowned self] _ in
            print("My text : \(self.textField.text ?? "")")
        }).disposed(by: bag)
Related