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

非 Y 不嫁゛ 提交于 2020-03-18 03:30:19

问题


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!


回答1:


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




回答2:


You can add controlEvents to asObservable:

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



回答3:


When you wish to observe a property of key-value observing compatible object, just call observe!

Here is an example

textfield.rx.observe(String.self, "text").subscribe(onNext: { s in
    print(s ?? "nil")
}).disposed(by: disposeBag)

This will detect changes to text that are made by both the user and your code.

You can use this technique to not just observe text, but also any other property that has a key path!




回答4:


If u are setting textfield.text programmatically then you can perform any actions over there. You don't need the subscription block.

As textfield is in inactive state your textfield.text subscription won't get called, rather u have to observe the textfield text.

Use bindings for text changes will solve your problem.

let textChange = Variable(true)
_ = textChange.asObservable().bindTo(textfield.rx.text)


来源:https://stackoverflow.com/questions/45633173/how-do-you-get-a-signal-every-time-a-uitextfield-text-property-changes-in-rxswif

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!