RxSwift - UITextField 以编程方式更新时未更新 UILabel 字段 [英] RxSwift - UILabel field not being updated when UITextField updated programmatically
问题描述
我只是在学习 RxSwift 并且有一个简单的例子,我不确定为什么它不起作用.我有一个文本字段和一个标签字段.每当文本字段更改时,我都希望更新标签字段.如果我在文本字段中输入,一切都会按预期进行.如果我以编程方式设置文本字段,例如当我按下按钮并显式设置文本字段时,标签字段不会更新.
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.
推荐答案
将您的代码更改为:
@IBAction func pBtn(sender: UIButton) {
myTextField.text = "45"
myTextField.sendActionsForControlEvents(.ValueChanged)
}
由于文本是一个属性,因此没有一种机制可以知道何时以编程方式更改它.相反,RxCocoa 使用控制事件来知道值何时发生变化.看看 UIControl+RxSwift.swift ,你会发现这样的东西:
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()))
}
这篇关于RxSwift - UITextField 以编程方式更新时未更新 UILabel 字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!