1

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.

  • Could you check this link - https://stackoverflow.com/a/51814368/3683408? Maybe it will can help you. – Ram Mar 13 '20 at 12:45

1 Answers1

1

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
    }
}
Daniel T.
  • 32,821
  • 6
  • 50
  • 72