简体   繁体   English

RxSwift / RxCocoa:防止UITextField包含超过…个字符

[英]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. 我想用RxSwift / RxCocoa配置一个UITextField,以便它最多只包含...个字符。 I do not want to use the UITextFieldDelegate for this but would love to achieve this with RxSwift/RxCocoa. 我不想为此使用UITextFieldDelegate ,但希望通过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. 在此示例中,文本字段限制为40个字符。

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. 但是请注意,当达到字符数限制时,光标将跳到textField的末尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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