简体   繁体   中英

RxSwift/RxCocoa: prevent UITextField from having more than … characters

I would like to have a UITextField configured with RxSwift/RxCocoa so that it only contains up to ... characters. I do not want to use the UITextFieldDelegate for this but would love to achieve this with RxSwift/RxCocoa. Is there a way to do this?

Sure:

textField.rx.controlEvent(.editingChanged).subscribe(onNext: { [unowned self] in
    if let text = self.textField.text {
        self.textField.text = String(text.prefix(40))
    }
}).disposed(by: disposeBag)

In this example, the textfield is limited to 40 characters.

Edit:

Keeping the previous value when the limit is reached.

textField.rx.text.orEmpty
.scan("") { (previous, new) -> String in
    if new.count > 40 {
        return previous ?? String(new.prefix(40))
    } else {
        return new
    }
}
.subscribe(textField.rx.text)
.disposed(by: disposeBag)

This can probably be adapted to respect other rules...

Please note however that when reaching the character limit, your cursor will jump to the end of the textField.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM