一般要求用户输入的内容都有长度的判定
可以在
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string;
这个代理方法里面来处理
但是这样处理不准确,如果是汉语输入最后几个字可能拼不出来
我的处理方法如下
[self.urlTextFieldaddTarget:selfaction:@selector(textEditingChanged:)forControlEvents:UIControlEventEditingChanged];
- (void)textEditingChanged:(UITextField*)textField{
NSIntegerMAX_STARWORDS_LENGTH =50;//这个根据自己需求来改,还可以根据textField来动态改
NSString*toBeString = textField.text;
NSString*lang = [textField.textInputModeprimaryLanguage];
if([langisEqualToString:@"zh-Hans"]) {//简体中文输入
//获取高亮部分
UITextRange*selectedRange = [textFieldmarkedTextRange];
UITextPosition*position = [textFieldpositionFromPosition:selectedRange.startoffset:0];
//没有高亮选择的字,则对已输入的文字进行字数统计和限制
if(!position || !selectedRange){
if(toBeString.length> MAX_STARWORDS_LENGTH){
NSRangerangeIndex = [toBeStringrangeOfComposedCharacterSequenceAtIndex:MAX_STARWORDS_LENGTH];
if(rangeIndex.length==0.5) {
textField.text= [toBeStringsubstringToIndex:MAX_STARWORDS_LENGTH];
[EGCPostViewnomalPostWithString:[NSStringstringWithFormat:@"最多%ld字",(long)MAX_STARWORDS_LENGTH]];
}else{
NSRangerangeRange = [toBeStringrangeOfComposedCharacterSequencesForRange:NSMakeRange(0, MAX_STARWORDS_LENGTH)];
textField.text= [toBeStringsubstringWithRange:rangeRange];
}
}
}
}//中文输入法以外的直接对其统计限制即可,不考虑其他语种情况
else{
if(toBeString.length> MAX_STARWORDS_LENGTH){
NSRangerangeIndex = [toBeStringrangeOfComposedCharacterSequenceAtIndex:MAX_STARWORDS_LENGTH];
if(rangeIndex.length==0.5){
textField.text= [toBeStringsubstringToIndex:MAX_STARWORDS_LENGTH];
}
else{
NSRangerangeRange = [toBeStringrangeOfComposedCharacterSequencesForRange:NSMakeRange(0, MAX_STARWORDS_LENGTH)];
textField.text= [toBeStringsubstringWithRange:rangeRange];
}
}
}
}
亲测对UITextVIew同样有效