Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing the 'next' option in the keyboard for iPhone SDK

Tags:

iphone

I am having an awful hard time trying to implement the task of when the user selects the 'next' button in the keyboard, the user is then sent to the next text field to start editing. In my example I have three text fields. Here is what I've done, hopefully you can fill me in on where I am going wrong. Keep in mind I just picked up SDK a few weeks ago so that may be part of the problem :)

In my ViewControler.h file I have created the following method

-(IBAction)nextPressed:(id) sender;

In my ViewController.m file, I have created the following action

-(IBAction)nextPressed:(id) sender 
{
    if ([txtUserName isFirstResponder]) 
    {
        [txtUserName2 becomeFirstResponder];
    }
    if ([txtUserName2 isFirstResponder]) 
    {
        [txtUserName3 becomeFirstResponder];
    }
}

In my .xib file, I have linked the first text field (right clicking on the text field and dragging to Files Owner and selecting the 'nextPressed:' option under Events) to my File Owner. I have tried linking to just the first text field and when that didn't work all of the three text fields. I've also tried linking not to the File's Owner but First Responder for one text field, then all of the text fields, with no luck. Also, for each text field I have selected the Return Key as 'NEXT'.

Now when I Build/Run I am able to edit the text field and see the 'next' button in the lower right, however it doesn't move me to the next field.

What step am I doing wrong here? I used instructions from this post (How do you change the UIControl with focus on iPhone?) but seem to be missing something huge here.

Any help with this would be greatly appreciated. I've been staring at this for the past four hours and Googling every possible search term I can come up with and can't easily wrap my head around the steps needed to accomplish this. Again, and help would be very helpful :)

like image 427
Zach Smith Avatar asked Nov 28 '22 11:11

Zach Smith


1 Answers

I don't think you need to define a separate selector nextPressed: - instead, implement the UITextFieldDelegate protocol method textFieldShouldReturn: to look something like:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if(textField == txtUserName) {
        [txtUserName2 becomeFirstResponder];
    } else if(textField == txtUserName2) {
        [txtUserName3 becomeFirstResponder];
    }
    return NO;
}

That particular method watches for when the Enter key (in your case, a Next key) is pressed. Once that's implemented, just set the delegate for each of the three text fields to the implementing class (probably your view controller), and you should be good.

like image 136
Tim Avatar answered Dec 17 '22 13:12

Tim