輸入框中的字符串長度限制問題,用到的地方很多。
通常情況會使用textfield的這個代理方法:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let nsString = textField.text as NSString?
if let replaced = nsString?.replacingCharacters(in: range, with: string) {
if textField == self.messageTextField {
return (replaced.characters.count <= 20)
}
return true
}
這個方法會在每次textfield中有輸入的時候被調(diào)用迁霎,在這個方法中做截取吱抚,看似沒有問題。
但在遇到中文輸入法的時候考廉,問題就會出現(xiàn):這里以使用蘋果原生的簡體中文拼音輸入法為例秘豹,textfield的限制為5個字?jǐn)?shù),當(dāng)輸入完前4個字的時候昌粤,最后一個中文字既绕,打出拼音的第一個英文字母時,就會被截取涮坐,導(dǎo)致最后一個中文字永遠(yuǎn)無法正確拼寫出來凄贩。
WechatIMG1.jpeg
因為在拼音的時候,還在拼寫并顯示在屏幕上的字母屬于marked text袱讹,會被
shouldChangeCharactersIn這個方法強制獲取到疲扎,而我們并不希望沒有完成拼寫的英文字母被獲取,所以只能采用以下辦法:
先創(chuàng)建一個針對textfield的監(jiān)聽(注意使用UITextFieldTextDidChangeNotification):
NotificationCenter.default.addObserver(self, selector:
#selector(self.greetingTextFieldChanged), name:
NSNotification.Name(rawValue:
"UITextFieldTextDidChangeNotification"),
object: self.messageTextField)
觸發(fā)方法的實現(xiàn)(關(guān)鍵代碼textField.markedTextRange廓译,判斷當(dāng)有markedtext的時候我們不做任何動作):
func greetingTextFieldChanged(obj: Notification) {
let textField: UITextField = obj.object as! UITextField
guard let _: UITextRange = textField.markedTextRange else{
if (textField.text! as NSString).length > 5{
textField.text = (textField.text! as NSString).substring(to: 5)
}
return
}
}
最后別忘了在銷毀的方法里把監(jiān)聽給注銷了:
deinit {
NotificationCenter.default.removeObserver(self, name:
NSNotification.Name(rawValue:
"UITextFieldTextDidChangeNotification"), object: self.messageTextField)
}
希望對你有所幫助评肆,謝謝