Instead of changing the text value with textField.text
, you have to create a signal, bind it to the text field and modify the signal's value. I've used a Signal
pipe but if you need to store the programmatically changed value, you can use a 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)
}
}