在不少狀況下都會要求限制輸入框的字數長度,在非中文狀況下簡單的處理下便可,但在系統自帶的中文輸入發現你會發現,即便輸入拼音也會被限制。咱們須要對中文輸入法進行單獨的設置:
1.給UITextField綁定一個方法:
[_summaryField addTarget:self action:@selector(editChange:) forControlEvents:UIControlEventEditingChanged];
2.實現方法code
//最多輸入6個字 #define kMaxLength 6 - (void)editChange:(UITextField*)textfield { NSString *toBeString = textfield.text; NSString *lang = [[UIApplication sharedApplication]textInputMode].primaryLanguage; // 鍵盤輸入模 if ([lang isEqualToString:@"zh-Hans"]) { // 簡體中文輸入,包括簡體拼音,健體五筆,簡體手寫 UITextRange *selectedRange = [textfield markedTextRange]; //獲取高亮部分 UITextPosition *position = [textfield positionFromPosition:selectedRange.start offset:0]; // 沒有高亮選擇的字,則對已輸入的文字進行字數統計和限制 if (!position) { if (toBeString.length > kMaxLength) { NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:kMaxLength]; if (rangeIndex.length == 1) { textfield.text = [toBeString substringToIndex:kMaxLength]; } else { NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, kMaxLength)]; textfield.text = [toBeString substringWithRange:rangeRange]; } } } } // 中文輸入法之外的直接對其統計限制便可,不考慮其餘語種狀況 else{ if (toBeString.length > kMaxLength) { NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:kMaxLength]; if (rangeIndex.length == 1) { textfield.text = [toBeString substringToIndex:kMaxLength]; } else { NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0,kMaxLength)]; textfield.text = [toBeString substringWithRange:rangeRange]; } } }```
做者:夢裏挑燈看鍵
連接:https://www.jianshu.com/p/7cb8bfde2778
來源:簡書
簡書著做權歸做者全部,任何形式的轉載都請聯繫做者得到受權並註明出處。get