06.RxSwift textFiled和textView的差异

387 阅读1分钟
override func viewDidLoad() {
        super.viewDidLoad()
	    // 1: textFiled & textView来了
        // 2: why 来两次
        textFiled.rx.text.subscribe(onNext: { (text) in
            print("输入来了 \(text)")
        })
        textView.rx.text.subscribe(onNext: { (text) in
            print("textView:输入来了 \(text)")
        })
        textFiled.addTarget(self, action: #selector(textFiledChange), for: .allEditingEvents)
}

@objc func textFiledChange() {
        print("laile")
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        textFiled.text = "LiHua"
        //textFiled.sendActions(for: .allEditingEvents)
        textView.text = "LiMing"
}
  • 问题一:刚运行起来就会打印:

textFiled输入来了 Optional("") textView:输入来了 Optional("Lorem ipsu...

原因是:初始化序列的时候 -> 默认会发送一次.onNext,让信号成为热信号(激活) 解决办法:加一个skip(1)即可,防止创建的时候默认调用一次

//加一个skip(1)即可,防止创建的时候默认调用一次
 textFiled.rx.text.skip(1). subscribe(onNext: { (text) in
      print("输入来了 \(text)")
 })
  • 问题二:执行赋值textFiled.text = "LiHua"textView.text = "LiMing" 却只有一个打印了 运行结果如下:

textView:输入来了 Optional("LiMing")

原因是:Rx内部textView.texttextFiled.text处理不一样

  • textView.text 内部使用的是 uses text storage notification储存通知
/// Reactive wrapper for `text` property.
    public var value: ControlProperty<String?> {
        let source: Observable<String?> = Observable.deferred { [weak textView = self.base] in
            let text = textView?.text
            let textChanged = textView?.textStorage
                // This project uses text storage notifications because
                // that's the only way to catch autocorrect changes
                // in all cases. Other suggestions are welcome.
                .rx.didProcessEditingRangeChangeInLength
                // This observe on is here because text storage
                // will emit event while process is not completely done,
                // so rebinding a value will cause an exception to be thrown.
                .observeOn(MainScheduler.asyncInstance)
                .map { _ in
                    return textView?.textStorage.string
                }
                ?? Observable.empty()
            
            return textChanged
                .startWith(text)
        }

  • textFiled.text 使用的是Events,只是做了赋值操作
 /// Reactive wrapper for `text` property.
    public var value: ControlProperty<String?> {
        return base.rx.controlPropertyWithDefaultEvents(
            getter: { textField in
                textField.text
            },
            setter: { textField, value in
                // This check is important because setting text value always clears control state
                // including marked text selection which is imporant for proper input 
                // when IME input method is used.
                if textField.text != value {
                    textField.text = value
                }
            }
        )
    }

解决办法: RxSwiftgitHubIssues一栏有如下:

即:设置textFiled.sendActions(for: .allEditingEvents)

 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        textFiled.text = "LiHua"
        textFiled.sendActions(for: .allEditingEvents)
        textView.text = "LiMing"
    }