Set custom UITextField max length

2019-08-18 06:14发布

问题:

I can't find a solution on my problem because all other posts at stackOverflow refer to UITextField created with the IDE and not programmatically.

I have a custom UITextField created inside (void)viewDidLoad.I have this created programmatically so i can access the leftView property.

    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 66, screenAdj, 30)];
    textField.borderStyle = UITextBorderStyleRoundedRect;
    textField.font=[UIFont fontWithName:@"Helvetica" size:14];
    textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    textField.returnKeyType = UIReturnKeyDone;
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [textField addTarget:self action:@selector(textFieldShouldReturn:)forControlEvents:UIControlEventEditingDidEndOnExit];
    textField.text=[defaults stringForKey:@"username"];

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
    label.font=[UIFont fontWithName:@"Helvetica" size:14];
    label.text = @"Your name";
    label.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.0];
    textField.leftViewMode = UITextFieldViewModeAlways;
    textField.leftView = label;

I also want to limit the max characters inside the TextField implementing:

- (BOOL)textField:(UITextField *) textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    NSUInteger oldLength = [textField.text length];
    NSUInteger replacementLength = [string length];
    NSUInteger rangeLength = range.length;

    NSUInteger newLength = oldLength - rangeLength + replacementLength;

    BOOL returnKey = [string rangeOfString: @"\n"].location != NSNotFound;

    return newLength <= MAX_LENGTH_USERNAME || returnKey;
}

But i realized that my textField doesn't "see" the above function.Tried with

[textField addTarget:self action:@selector(...

but no luck. Any help?

回答1:

You have to tell your view controller to conform to UITextFields delegate protocol. In your (.h) add <UITextFieldDelegate> right after "UIViewController", and when you set up your text field set its delegate to self:

[textField setDelegate:self];

Then you can go ahead and remove this line

[textField addTarget:self action:@selector(...

Assuming you were using this to call shouldChangeCharactersInRange. Now that you've set up the delegate, this method will be called automatically.