Search code examples
iosswiftrx-swift

How to implement shouldChangeTextIn the RxSwift way


Is there a way to implement the shouldChangeTextIn UITextView's delegate method in RxSwift way? My goal is to limit the text input of the user. I just have this:

    self.textView.rx.text
        .orEmpty
        .scan("") { (previous, new) -> String in
            return new.count > 254 ? previous : new
        }
        .bind(to: self.viewModel.notes)
        .disposed(by: self.disposeBag)

This is for data, but I don't know how to prevent the further input after 254 count.

I also found RxTextViewDelegateProxy but I'm not sure too how to use it.

let rxTVDelegateProxy = RxTextViewDelegateProxy(textView: self.textView)

Solution

  • Try this:

           textView.rx.text.orEmpty
            .scan("") { (previous, new) -> String in
    
                return new.count < 254 ? new : previous ?? String(new.prefix(254))
            }
            .bind(to: textView.rx.text)
            .disposed(by: disposeBag)