UITextField在输入时限制中文输入的长度
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string {
UITextRange*selectedRange = [textFieldmarkedTextRange];
//获取高亮部分
UITextPosition*position = [textFieldpositionFromPosition:selectedRange.startoffset:0];
NSString* str =@"";
if(selectedRange){
str = [textFieldtextInRange:selectedRange];
}
if([stringisEqualToString:@""])
returnYES;
if(position) {//有高亮
if(range.length==0) {//还在输入
if(textField.text.length- str.length>=_limitCount) {
NSString* toBestring = [textField.textstringByReplacingCharactersInRange:rangewithString:str];
toBestring = [toBestringsubstringWithRange:[toBestring rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, _limitCount)]];;;
self.alertInput.text= toBestring;
[selfzt_showHint:[NSStringstringWithFormat:@"最多%ld字符",_limitCount] yOffset:-200];
returnNO;
}else{
returnYES;
}
}else{//选中键盘上的中文
NSString* toBestring = [textField.textstringByReplacingCharactersInRange:rangewithString:string];
if(toBestring.length>_limitCount) {
toBestring = [toBestringsubstringWithRange:[toBestring rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, _limitCount)]];;;
self.alertInput.text= toBestring;
[selfzt_showHint:[NSStringstringWithFormat:@"最多%ld字符",_limitCount] yOffset:-200];
returnNO;
}
returnYES;
}
}else{//没高亮
if((textField.text.length+ string.length) >_limitCount){
[selfzt_showHint:[NSStringstringWithFormat:@"最多%ld字符",_limitCount] yOffset:-200];
returnNO;
}
}
return YES;
}