iosuikit

How I tell my UITextField (code) to resign first responder?


I have created my UITextField by code, without InterfaceBuilder. I want the keyboard to disappear when the button "Done" is pushed. How does the code know that I am referending to an UITextField and no to other one


First, thanks a lot.

My code is like this:

-(void)viewDidLoad {
    [super viewDidLoad];
    field = [[UITextField alloc] initWithFrame:CGRectMake(30, 100, 185, 30)];
    field.adjustsFontSizeToFitWidth = YES;
    field.textColor = [UIColor blackColor];
    field.placeholder = @"Text";
    field.keyboardType = UIKeyboardTypeDefault;
    field.returnKeyType = UIReturnKeyDone;
    field.backgroundColor = [UIColor blueColor];
    field.delegate = self;
    [self.view addSubview:field];
} 

......

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];

}

With this code I push the button Done and nothing happen. Is like that how you say?

Edit:

I've created two UITextField how I did with the previous one. But now, for each row I do this:

 if ([indexPath row] == 0) {
     [cell.contentView addSubview:pTextField];
 }
 else {
     [cell.contentView addSubview:pTextField];
 }

So with this code, the program received signal "EXC_BAD_ACCESS". Any idea why happen this?


Solution

  • How does the code know that I am referending to an UITextField and no to other one

    Your textFieldShouldReturn: method's textField parameter will always be the text field that is currently active.

    The method has to return a BOOL, you should be getting compiler warnings with it as it stands. Try

    -(BOOL)textFieldShouldReturn:(UITextField *)textField
    {
        [textField resignFirstResponder];
        return YES;
    }
    

    Note that you are also currently leaking memory in the way you add the text field. You should set it as a property as per WrightCS's answer so that you can refer to it later on. So at the end of your viewDidLoad:

    self.myTextField = field;
    [field release];