Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxSwift - UILabel field not being updated when UITextField updated programmatically

I'm just learning RxSwift and have a simple example that I'm not sure why it is not working. I have a text field and a label field. ANY time the text field changes, I'd like the label field to be updated. If I type in the text field, everything works as expected. If I set the text field programmatically, such as when I push a button and set the text field explicitly, 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 to update? I've looked at a lot of examples but can't seem to find one that answers this question.

like image 304
dfrobison Avatar asked Nov 19 '15 22:11

dfrobison


1 Answers

Change your code to this:

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

Since text is a property, there isn't a mechanism to know when it is changed programmatically. Instead, RxCocoa uses control events to know when the value has changed. Have a look in UIControl+RxSwift.swift and you'll find something like this:

let controlTarget = ControlTarget(control: control, controlEvents: [.EditingChanged, .ValueChanged]) {
  control in
    observer.on(.Next(getter()))
}
like image 128
louoso Avatar answered Nov 23 '22 05:11

louoso