iPhone SDK – Keyboard next button

328th Feb 2010iPhone Apps, Systems Administration, ,

One thing that has alluded me in my iPhone development is when entering details into text inputs, being able to hit “Next” in the native keyboard to actually go to the next text input box, sounds simple doesn’t it?

In the Interface Builder there is “tag” variable you can give to each input, say “0” for the first text input, “1” for the next, “2” for the one after that etc but this doesn’t actually do anything…

There is a function you can use in your .m called “textFieldShouldReturn” this is where we would typically have something like:

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

Which isn’t much help, what we actually want is something like:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
   NSInteger nextTag = textField.tag + 1;
   UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
   if (nextResponder) {
       [nextResponder becomeFirstResponder];
   }
   else{
       [textField resignFirstResponder];
   }
   return YES;
}

This method is almost exactly the same as the first but has one extra step, rather than just setting [textField resignFirstResponder] is looks to see if there is a text field with a tag id one greater than the one being edited currently, if this is the case then set [nextResponder becomeFirstResponder];

3 Comments Comments Feed

  1. Rachit Shah (March 8, 2010, 1:27 pm).

    Hi Harry,

    I am looking to use for Navigation in TextField input screen.
    I have tried to put textFieldShouldReturn function in .m file but it did not directly work. How to do do that?
    I think there is need some routine to add tag value to different textField Inputs..
    Thanks,
    Rachit

  2. Jason (April 27, 2010, 3:00 am).

    Helpful! Thank you!

  3. Matthias (September 13, 2010, 12:18 pm).

    Realy usefull! Thanks!

Add a Comment

*

Spam protection by WP Captcha-Free