Set the maximum character length of a UITextField

前端 未结 30 2063
难免孤独
难免孤独 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 02:48

    Thank you august! (Post)

    This is the code that I ended up with which works:

    #define MAX_LENGTH 20
    
    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
        if (textField.text.length >= MAX_LENGTH && range.length == 0)
        {
            return NO; // return NO to not change text
        }
        else
        {return YES;}
    }
    

提交回复
热议问题