How can I set the maximum amount of characters in a UITextField
on the iPhone SDK when I load up a UIView
?
This is the correct way to handle max length on UITextField, it allows the return key to exit the resign the textfield as first responder and lets the user backspace when they reach the limit
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
int MAX_LENGHT = 5;
if([string isEqualToString:@"\n"])
{
[textField resignFirstResponder];
return FALSE;
}
else if(textField.text.length > MAX_LENGHT-1)
{
if([string isEqualToString:@""] && range.length == 1)
{
return TRUE;
}
else
{
return FALSE;
}
}
else
{
return TRUE;
}
}