views:

373

answers:

2

Hello,

Is there any way to set the maximum length on a UITextField?

Something like the MAXLENGTH attribute in HTML input fields.

+4  A: 

I think you mean UITextField. If yes, then there is a simple way.

  1. Implement the UITextFieldDelegate protocol
  2. Implement the textField:shouldChangeCharactersInRange:replacementString: method.

That method gets called on every character tap or previous character replacement. in this method, you can do something like this:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([textField.text length] > MAXLENGTH) {
        textField.text = [textField.text substringToIndex:MAXLENGTH-1];
        return NO;
    }
    return YES;
}
coneybeare
Yes I was meaning UITextField, I edited my question.I got it. Thanks for your answer. It works for me !
Christophe Konig
A: 

I think there's no such property.

But the text you assign to the UILabel has to be an NSString. And before you assign this string to the UILabel's text property you can for example use the following method of NSString to crop the string at a given index (your maxlength):

- (NSString *)substringToIndex:(NSUInteger)anIndex
schaechtele