textField.text
您必须创建一个信号,将其绑定到文本字段并修改信号的值,而不是用 更改文本值。我使用了Signal
管道,但如果您需要存储以编程方式更改的值,您可以使用MutableProperty
.
class MyViewController: UIViewController {
var textField: UITextField!
private let textFieldValuePipe = Signal<String?, NoError>.pipe()
var textFieldValueSignal: Signal<String?, NoError>!
override func viewDidLoad() {
// Initialize the text field
// ...
// Bind the text of the text field to the signal pipe's output
textField.reactive.text <~ textFieldValuePipe.output
// A signal of text values emitted by the text field upon end of editing.
let textFieldValuesSignal = textField.reactive.textValues
// A signal of text values emitted by the text field upon any changes.
let textFieldContinuousValuesSignal = textField.reactive.continuousTextValues
// Merge the relevant signals
textFieldValueSignal = Signal.merge(textFieldValuesSignal, textFieldContinuousValuesSignal, textFieldValuePipe.output)
// This will print the text field's value when it's changed by the user or programmatically
textFieldValueSignal.observeValues { value in
print(value ?? "nil")
}
}
// Use this to change the text field's value programmatically
func setTextFieldText(_ text: String?) {
textFieldValuePipe.input.send(value: text)
}
}