說到限制輸入框的字數限制,你們都會想到在textFieldDelegate的代理方法中進行判斷。那若是是用RxSwift,該怎麼實現呢?咱們直接來看代碼:bash
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)
複製代碼
怎麼樣,是否是簡單多了?ui