说到限制输入框的字数限制,大家都会想到在textFieldDelegate的代理方法中进行判断。那如果是用RxSwift,该怎么实现呢?我们直接来看代码:
let countValid = priceField.rx.text.orEmpty.map { text -> Bool in
text.count > 10
}.share(replay: 1)
countValid.subscribe(onNext: { valid in
if valid {
let index = self.priceField.text!.index(self.priceField.text!.startIndex, offsetBy: 10)
self.priceField.text = String(self.priceField.text![..<index])
}
}).disposed(by: bag)
怎么样,是不是简单多了?