今天在寫一個限制UITextField漢字數量的需求,原覺得很是簡單的一個需求,在實際開發中遇到了不少問題.css
首先,漢字的輸入時的聯想詞在輸入到TextFiled時,並不會走app
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;測試
這致使了在這裏進行長度限制的代碼都會失效.此路不通.spa
通過查找資料,得知能夠用註冊UITextFieldTextDidChangeNotification
通知來監測TextField的文字的變化code
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:) name:@"UITextFieldTextDidChangeNotification" object:myTextField];
在textFiledEditChanged:方法中server
- (void)textDidChanged:(NSNotification *)notification{ NSInteger maxLength = 6; UITextField *textField = (UITextField *)notification.object; if (textField.text.length > maxLength) { textField.text = [textField.text substringToIndex:maxLength]; } }
這種方法看起來沒什麼問題,然而實測在iOS7下輸入漢字時,一旦長度到達最大長度,再進行輸入(此時輸入狀態仍是拼音)就會當即崩潰.對象
*** Terminating app due to uncaught exception 'NSRangeException', reason: 'NSMutableRLEArray replaceObjectsInRange:withObject:length:: Out of bounds'blog
該問題在iOS8以上的系統中不會出現,多是蘋果修復了該BUG.開發
再次查找資料,找到這篇博客http://www.jianshu.com/p/2d1c06f2dfa4字符串
這篇博客解決了UItextFiled在截取字符串時,若是對emoji進行截取會變亂碼的問題(緣由是emoji實際上佔了3個長度).
UITextField *textField = (UITextField *)obj.object; NSString *toBeString = textField.text; //獲取高亮部分 UITextRange *selectedRange = [textField markedTextRange]; UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0]; // 沒有高亮選擇的字,則對已輸入的文字進行字數統計和限制 if (!position) { if (toBeString.length > MAX_STARWORDS_LENGTH) { NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:MAX_STARWORDS_LENGTH]; if (rangeIndex.length == 1) { textField.text = [toBeString substringToIndex:MAX_STARWORDS_LENGTH]; } else { NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, MAX_STARWORDS_LENGTH)]; textField.text = [toBeString substringWithRange:rangeRange]; } } }
測試後發現,這個方法在iOS8以上的系統運行良好,可是在iOS7下竟然徹底失效了.
緣由是在iOS7下,position對象老是不爲nil,致使走不進處理長度的代碼.
研究後發如今須要增長一個判斷條件,
改進後的代碼:
UITextField *textField = (UITextField *)obj.object; NSString *toBeString = textField.text; //獲取高亮部分 UITextRange *selectedRange = [textField markedTextRange]; UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0]; // 沒有高亮選擇的字,則對已輸入的文字進行字數統計和限制 if (!position || !selectedRange) { if (toBeString.length > MAX_STARWORDS_LENGTH) { NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:MAX_STARWORDS_LENGTH]; if (rangeIndex.length == 1) { textField.text = [toBeString substringToIndex:MAX_STARWORDS_LENGTH]; } else { NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, MAX_STARWORDS_LENGTH)]; textField.text = [toBeString substringWithRange:rangeRange]; } } }
再次測試後沒有發現崩潰問題了.