Set the maximum character length of a UITextField

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

    I simulate the actual string replacement that's about to happen to calculate that future string's length:

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
        NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
        if([newString length] > maxLength)
           return NO;
    
        return YES;
    }
    

提交回复
热议问题