Set the maximum character length of a UITextField

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

    Other answers do not handle the case where user can paste a long string from clipboard. If I paste a long string it should just be truncated but shown. Use this in your delegate:

    static const NSUInteger maxNoOfCharacters = 5;
    
    -(IBAction)textdidChange:(UITextField * )textField
    {
    NSString * text = textField.text;
    
    if(text.length > maxNoOfCharacters)
    {
        text = [text substringWithRange:NSMakeRange(0, maxNoOfCharacters)];
        textField.text = text;
    }
    
    // use 'text'
    
    }
    

提交回复
热议问题