Set the maximum character length of a UITextField

前端 未结 30 2109
难免孤独
难免孤独 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条回答
  •  Happy的楠姐
    2020-11-22 02:41

    To make it work with cut & paste of strings of any length, I would suggest changing the function to something like:

    #define MAX_LENGTH 20
    
    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
        {
            NSInteger insertDelta = string.length - range.length;
    
            if (textField.text.length + insertDelta > MAX_LENGTH)
            {
               return NO; // the new string would be longer than MAX_LENGTH
            }
            else {
                return YES;
            }
        }
    

提交回复
热议问题