第一步 新建textfield
_tf=[[UITextField alloc]initWithFrame:CGRectMake(50, 150, 200, 30)];
_tf.backgroundColor=[UIColor whiteColor];
_tf.delegate=self;//开代理
_tf.autocapitalizationType = UITextAutocapitalizationTypeNone;
[self.view addSubview:_tf];
[_tf addTarget:self action:@selector(infoAction:) forControlEvents:UIControlEventEditingChanged];
//实现监听
- (void)infoAction:(UITextField *)textField
{
NSString *toBeString = textField.text;
UITextRange *selectedRange = [textField markedTextRange];
//获取高亮部分
NSString *newText=[textField textInRange:selectedRange];
if (newText.length>0) {
return; //如果存在高亮部分则此时不计算textfield的文字长度
}else{
if ([self textLength:toBeString] >16) {
NSUInteger asciiLength = 0;
for (NSUInteger i = 0; i <textField.text.length; i++) {
unichar uc = [textField.text characterAtIndex: i];
asciiLength += isascii(uc) ? 1 : 2;
if (asciiLength==16) {
textField.text = [textField.text substringToIndex:i+1];
return;
}
if (asciiLength>16) {
textField.text = [textField.text substringToIndex:i];
return;
}
}
}
}
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if (self.tf == textField){
UITextRange *selectedRange = [textField markedTextRange];
NSString *newText=[textField textInRange:selectedRange];
if (newText.length>0) {
return YES;
}else{
if (string.length == 0) return YES;
NSUInteger existedLength =[self textLength:textField.text];
NSUInteger selectedLength = range.length;
NSUInteger replaceLength = string.length;
if (existedLength - selectedLength + replaceLength > 16) {
return NO;
}
}
}
return YES;
}
-(NSUInteger)textLength: (NSString *) text{
NSUInteger asciiLength = 0;
for (NSUInteger i = 0; i < text.length; i++) {
unichar uc = [text characterAtIndex: i];
asciiLength += isascii(uc) ? 1 : 2;
}
NSUInteger unicodeLength = asciiLength;
return unicodeLength;
}