RxSwift - UILabel field not being updated when UIT

2019-06-18 14:38发布

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.

1条回答
Ridiculous、
2楼-- · 2019-06-18 14:42

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()))
}
查看更多
登录 后发表回答