0

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?

Community
  • 1
  • 1
Theodoros80
  • 796
  • 2
  • 15
  • 43
  • why did you cut of the most important piece of code after all? [tff addTarget:self action:@selector(changed:) forControlEvents:UIControlEventEditingChanged]; is the thing you need. – jimpic Nov 26 '12 at 15:27
  • try textField.delegate = self; and the viewcontroller implemets shouldChangeCharactersInRange; – zt9788 Nov 26 '12 at 15:30
  • Jimpic it didn't work.But i got my solution,thanks anyway. – Theodoros80 Nov 26 '12 at 15:34

1 Answers1

2

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.

Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281