user4595813
user4595813

Reputation:

RxSwift Control Event with UITextFieldDelegate

I am using RxSwift for a project. I am using the control events to handle the textfield events such as follows.

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

Now I need to handle a delegate method

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

If I add the delegate to the textField, the controlEvents stop working.

Does anybody have a suggestion about how can I handle this case where I can use both the control events and delegate methods?

Or should I just remove either of these handling.

Thanks.

Upvotes: 1

Views: 1077

Answers (1)

Daniel T.
Daniel T.

Reputation: 33967

The editingDidEndOnExit control event stops working because the delegate is changing the behavior of the return key. Add a textFieldShouldReturn(_:) to your delegate and have it return true, then the controlEvent will work as expected.

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

Upvotes: 1

Related Questions