2

I want to set a limit for characters in a textFiled using RxSwift, may be i can benefit from Scan operator but i don't know how to use it in this case ,

I want my resulting code to behave as same as implementing it in shouldChangeCharacterInRage method:

   func textField(_ textField: UITextField,
                   shouldChangeCharactersIn range: NSRange,
                   replacementString string: String)
        -> Bool {
            if textField == baseTextFiled{
                let enteredString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
                if enteredString.count > limit{ // limit defined previously
                    return false
                }
            }
            return true
    }

Any help?

mojtaba al moussawi
  • 1,360
  • 1
  • 13
  • 21

1 Answers1

1

ReactiveX pushes data, so isn't really compatible with that particular delegate method. That said, you can still do it because .rx.text is a control property...

baseTextField.rx.text.orEmpty          // pushes text
    .map { String($0.prefix(limit)) }  // pushes first X characters in text
    .distinctUntilChanged()            // only pushes if text is different than previously
    .bind(to: baseTextField.rx.text)   // pushes text into text field
    .disposed(by: bag)
Daniel T.
  • 32,821
  • 6
  • 50
  • 72