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?

1
  • What did you try?
    – E-Riddie
    Commented Sep 3, 2018 at 14:52

1 Answer 1

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)
1
  • thx Daniel for the help however your solution work only if i remove distinctUntilChanged() Commented Sep 4, 2018 at 6:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.