RxSwift - UILabel field is not updated when UITextField is updated programmatically

I am just learning RxSwift and have a simple example that I'm not sure why it is not working. I have a text box and a label box. Anytime a text field changes, I need to update the label field. If I type a text box, everything works as expected. If I program a text field, for example, when I press a button and explicitly set a text field, the label field is not updated.

import UIKit import RxSwift import RxCocoa class ViewController: UIViewController { @IBOutlet weak var myTextField: UITextField! @IBOutlet weak var myLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() myTextField.rx_text.bindTo(myLabel.rx_text) } @IBAction func pBtn(sender: UIButton) { myTextField.text = "45" } } 

How do I get the label field for an update? I looked through many examples, but I can not find the answer to this question.

+5
source share
1 answer

Change the code as follows:

 @IBAction func pBtn(sender: UIButton) { myTextField.text = "45" myTextField.sendActionsForControlEvents(.ValueChanged) } 

Since text is a property, there is no mechanism to know when it changes programmatically. Instead, RxCocoa uses control events to know when a value has changed. Take a look at UIControl + RxSwift.swift and you will find something like this:

 let controlTarget = ControlTarget(control: control, controlEvents: [.EditingChanged, .ValueChanged]) { control in observer.on(.Next(getter())) } 
+16
source

Source: https://habr.com/ru/post/1236375/


All Articles