RxSwift - UILabel field not being updated when UITextField updated programmatically

与世无争的帅哥 提交于 2019-12-08 17:32:08

问题


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:


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()))
}


来源:https://stackoverflow.com/questions/33815399/rxswift-uilabel-field-not-being-updated-when-uitextfield-updated-programmatica

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