Set the maximum character length of a UITextField

前端 未结 30 1651
难免孤独
难免孤独 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:49

    Got it down to 1 line of code :)

    Set your text view's delegate to "self" then add the in your .h and the following code in your .m .... you can adjust the number "7" to be whatever you want your MAXIMUM number of characters to be.

    -(BOOL)textView:(UITextView *)a shouldChangeTextInRange:(NSRange)b replacementText:(NSString *)c {
        return ((a.text.length+c.length<=7)+(c.length<1)+(b.length>=c.length)>0);
    }
    

    This code accounts for typing new characters, deleting characters, selecting characters then typing or deleting, selecting characters and cutting, pasting in general, and selecting characters and pasting.

    Done!






    Alternatively, another cool way to write this code with bit-operations would be

    -(BOOL)textView:(UITextView *)a shouldChangeTextInRange:(NSRange)b replacementText:(NSString *)c {
        return 0^((a.text.length+c.length<=7)+(c.length<1)+(b.length>=c.length));
    }
    

提交回复
热议问题