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

别说谁变了你拦得住时间么 提交于 2019-12-18 19:42:28

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/48790405/rxswift-rxcocoa-prevent-uitextfield-from-having-more-than-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!