9

您如何从用户启动的和以编程方式对UITextField text属性进行的更改中获取信号?通过使用continuousTextValues仅在用户启动更改时报告信号。如果您textField.text以编程方式设置,则不会触发信号。

这就是我的使用方式continuousTextValues

textField.reactive.continuousTextValues.observeValues { value in
    print("Value: \(value)")
}

text如果我手动设置它不会被触发:

textField.text = "Test"
4

4 回答 4

5

该信号continuousTextValues只会在用户使用键盘输入时触发。你可以试试这个:

var characters = MutableProperty("")

tf.reactive.text <~ characters
tf.reactive.continuousTextValues.observeValues { [weak characters = characters] (text) in
   characters?.value = text!
}
tf.reactive.textValues.observeValues { [weak characters = characters] (text) in
   characters?.value = text!
}

characters.producer.skip(while: { $0.isEmpty }).startWithValues { (text) in
   log.debug("text = \(text)")
}

characters.value = "shaw"
于 2017-01-06T10:09:21.867 回答
1

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

}
于 2017-02-18T03:03:16.150 回答
0

要侦听文本属性中的编程更改:

let textField = UITextField()
let signal = textField.reactive.signal(forKeyPath: #keyPath(UITextField.text)).map { $0 as? String }
signal.observeValues { print($0) }
textField.text = "Hello World"

continuousTextValues请注意,如果您想观察由于用户操作而发生的变化,您仍然需要观察。

于 2018-02-24T06:20:13.873 回答
0

设置好文字后,触发编辑事件:textField.sendActions(for: .editingChanged)

于 2019-10-17T05:54:42.123 回答