在很多情況下都會要求限制輸入框的字數長度,在非中文情況下簡單的處理下即可晴叨,但在系統(tǒng)自帶的中文輸入發(fā)現你會發(fā)現凿宾,即使輸入拼音也會被限制。我們需要對中文輸入法進行單獨的設置:
1.給UITextField綁定一個方法:
[_summaryField addTarget:self action:@selector(editChange:) forControlEvents:UIControlEventEditingChanged];
2.實現方法
//最多輸入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];
// 沒有高亮選擇的字孙技,則對已輸入的文字進行字數統(tǒng)計和限制
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];
}
}
}
}
// 中文輸入法以外的直接對其統(tǒng)計限制即可产禾,不考慮其他語種情況
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];
}
}
}```