In the OC language, the NSString type of string, depending on the English alphabet and Chinese characters, is a length (String.Length a Chinese character as a length), whereas in fact an English letter occupies only 1 bytes and one Chinese character occupies 2 bytes.
Sometimes there is a need to qualify the number of bytes, rather than the number of content, and you need some way to get to the number of bytes in the string. For example, if you limit 10 bytes, you can enter up to 10 English letters or 5 characters.
Monitoring the length of TextField changes, you need to set the TextField agent.
But there's a bug, a proxy method for monitoring content changes
-(BOOL) TextField: (Uitextfield *) TextField Shouldchangecharactersinrange: (nsrange) range replacementstring: ( NSString *) string
In the click of the keyboard input is normal, but if you do not click the keyboard keys, take Chinese characters input examples, enter a word, the keyboard will appear with the word may be words, points above the words to enter, will not trigger the above proxy method.
So this proxy method is not available and we need to monitor by registering TextField notifications.
Registration notification, TextField content change Call
[[Nsnotificationcenter defaultcenter] addobserver:self selector: @selector ( Textfielddidchange:) name:uitextfieldtextdidchangenotification Object:self.testTextField];
Implementing Notification methods
-(void) Textfielddidchange: (nsnotification *) note{
Uitextfield *textfield = note.object;
Gets the number of bytes in the contents of the text box
int bytes = [self stringConvertToInt:self.testTextField.text];
The setting cannot exceed 32 bytes because there cannot be half Chinese characters, so the string length is the unit.
if (bytes >)
{
//exceeded the number of bytes, or the original content
self.testTextField.text = self.lasttextcontent;
}
else
{
self.lasttextcontent = self.testTextField.text;
}
}
Gets the byte number function
-(int) Stringconverttoint: (nsstring*) strtemp
{
int strlength = 0;
char* p = (char*) [strtemp cstringusingencoding:nsunicodestringencoding];
for (int i=0; i<[strtemp lengthofbytesusingencoding:nsunicodestringencoding]; i++)
{
if (*p) {
p++;
strlength++;
}
else {
p++;
}
}
Return (strlength+1)/2;
}
If TextField has content in the beginning, it needs to be acquired, using the proxy method
-(BOOL) textfieldshouldbeginediting: (Uitextfield *) TextField
{
self.lasttextcontent = Textfield.text;
Return YES
}
The above is a small set to introduce the iOS TextField limit byte length of the relevant content, I hope to help.