First step new TextField
_tf=[[uitextfield Alloc]initwithframe:cgrectmake (50, 150, 200, 30)];
_tf.backgroundcolor=[uicolor Whitecolor];
_tf.delegate=self;//Open Agent
_tf.autocapitalizationtype = Uitextautocapitalizationtypenone;
[Self.view ADDSUBVIEW:_TF];
The second step is to open the listening method for TextField
[_TF addtarget:self Action: @selector (infoaction:) forcontrolevents:uicontroleventeditingchanged];
Implementation Monitoring
-(void) Infoaction: (Uitextfield *) TextField
{
NSString *tobestring = Textfield.text;
Uitextrange *selectedrange = [TextField markedtextrange];
Get the highlighted section
NSString *newtext=[textfield Textinrange:selectedrange];
if (newtext.length>0) {
Return If there is a highlighted section, the TextField literal length is not computed at this time
}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
}
}
}
}
}
The third step is to set the proxy method
-(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;
}//Judge string length (Kanji two bytes)
-(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;
}