Set the maximum character length of a UITextField

前端 未结 30 1689
难免孤独
难免孤独 2020-11-22 02:27

How can I set the maximum amount of characters in a UITextField on the iPhone SDK when I load up a UIView?

30条回答
  •  悲&欢浪女
    2020-11-22 03:00

    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;
        }
    }
    

提交回复
热议问题