带有UITextFieldDelegate的RxSwift控制事件

问题描述 投票:1回答:1

我正在为项目使用RxSwift。我正在使用控件事件来处理文本字段事件,如下所示。

textField.rx.controlEvent([.editingDidEndOnExit]).subscribe {  _ in }.disposed(by: disposeBag)

现在我需要处理委托方法

textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool

如果将委托添加到textField,则controlEvents停止工作。

有人建议我如何处理可以同时使用控制事件和委托方法的情况吗?

或者我应该删除这两个处理中的一个。

谢谢。

ios swift rx-swift uitextfielddelegate
1个回答
0
投票

editingDidEndOnExit控制事件停止工作,因为委托人正在更改返回键的行为。将textFieldShouldReturn(_:)添加到您的代理中,并使其返回true,然后controlEvent将按预期方式工作。

extension ExampleViewController: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        // can only enter numbers with this. An example of the sort of thing you 
        //   might want to put in this method.
        return string.isEmpty || string.allSatisfy { !$0.unicodeScalars.contains { !NSCharacterSet.decimalDigits.contains($0) } }
    }

    // this method must exist. If you don't add a delegate to your text field, 
    //   the default behavior is as if this returned true. If you add a delegate, 
    //   then the field's default behavior changes to false and you have to 
    //   implement this method to get it to return true again.
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        return true
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.