iOS 限制输入字数完美解决方案
生活随笔
收集整理的這篇文章主要介紹了
iOS 限制输入字数完美解决方案
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
關于限制輸入字數以前也做過,網上也很多方法。
但都不夠完美,以前的測試人員也沒千方百計的挑毛病,所以就糊弄過去了。
現在這個項目的測試人員為了找bug真是無所不用其極。。。。
1.一般方法就是通過UITextField的代理方法
#pragma mark - UITextFieldDelegate- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {if (textField == self.textFieldName) {if (string.length == 0) return YES;NSInteger existedLength = textField.text.length;NSInteger selectedLength = range.length;NSInteger replaceLength = string.length;if (existedLength - selectedLength + replaceLength > 20) {return NO;}}return YES; }but這個方法還是有bug的。。。這個方法很容易被中文的聯想、粘貼等方式突破限制長度。
2.給UITextField加事件,然后在事件里截取至最大長度
[self.textFieldName addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];- (void)textFieldDidChange:(UITextField *)textField {if (textField == self.textFieldName) {if (textField.text.length > 15) {textField.text = [textField.text substringToIndex:15];}} }你以為這樣搞定了中文聯想、粘貼的bug,就高枕無憂了嗎。。。這方法還是有bug的,如果輸入至還剩一個字符時,再輸入Emoji呢?Emoji占2個字符,會被截得出現半個Emoji的情況,含半個Emoji的字符串在URL編碼時會變為nil。
3.限制輸入字數完美解決方案
其實就是在方案2上做了調整
- (void)textFieldDidChange:(UITextField *)textField {if (textField == self.textFieldName) {if (textField.text.length > 15) {UITextRange *markedRange = [textField markedTextRange];
??????? if (markedRange) {
??????????? return;
??????? }//Emoji占2個字符,如果是超出了半個Emoji,用15位置來截取會出現Emoji截為2半//超出最大長度的那個字符序列(Emoji算一個字符序列)的rangeNSRange range = [textField.text rangeOfComposedCharacterSequenceAtIndex:15];textField.text = [textField.text substringToIndex:range.location];}} }
?
轉載于:https://my.oschina.net/zhanglinfengzlf/blog/699205
總結
以上是生活随笔為你收集整理的iOS 限制输入字数完美解决方案的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 我目前在做的东西
- 下一篇: 网络 http服务器-v1-多线程版本