IOS textField limits the length of bytes

  • 2020-05-17 06:34:12
  • OfStack

In the OC language, strings of type NSString are regarded as 1 length for both English letters and Chinese characters (string.length treats a Chinese character as 1 length), while in fact, a single English letter only takes 1 byte and a Chinese character takes 2 bytes.

Sometimes there is a requirement to limit the number of bytes, not the number of contents, so you need to get the number of bytes in a string by some method. For example, limited to 10 bytes, you can enter up to 10 English letters, or 5 Chinese characters.

To listen for changes in the length of textField, you need to set up the agent for textField.

But there is an bug proxy method that listens for content changes


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

It is normal to input by clicking the keyboard, but if you do not click the keyboard key, take Chinese character input as an example. After typing a word, a word that may be a word will appear on the keyboard. If you click the word that appears on the keyboard to input, the proxy method above will not be triggered.

So this proxy method is not working, we need to register textField notifications to listen.


// Registration notice, textfield Content change call 
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChange:) name:UITextFieldTextDidChangeNotification object:self.testTextField];

Implement notification methods


- (void)textFieldDidChange:(NSNotification *)note{
UITextField *textField = note.object;
// Gets the number of bytes of text box content 
int bytes = [self stringConvertToInt:self.testTextField.text];
// Setting cannot exceed 32 Byte, because you can't have half a Chinese character, so the length of the string as a unit. 
if (bytes > 16)
{
// Out of the number of bytes, the original content 
self.testTextField.text = self.lastTextContent;
}
else
{
self.lastTextContent = self.testTextField.text;
}
}
// Get the number of bytes 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 textField1 has content from the beginning, get it, using the proxy method


- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
self.lastTextContent = textField.text;
return YES;
}

The above is the site to give you IOS textField limit the length of the byte related content, I hope to help you.


Related articles: