phx phx - 5 months ago 150
Swift Question

How to navigate through textfields (Next / Done Buttons)

How can I navigate through all my text fields with the "Next" Button on the iPhone Keyboard?

The last text field should close the Keyboard.

I've setup the IB the Buttons (Next / Done) but now I'm stuck.

I implemented the textFieldShouldReturn action but now the Next and Done Buttons close the Keyboard.

Thanks for your help!

Answer

In Cocoa for Mac OS X, you have the next responder chain, where you can ask the text field what control should have focus next. This is what makes tabbing between text fields work. But since iOS devices do not have a keyboard, only touch, this concept has not survived the transition to Cocoa Touch.

This can be easily done anyway, with two assumptions:

  1. All "tabbable" UITextFields are on the same parent view.
  2. Their "tab-order" is defined by the tag property.

Assuming this you can override textFieldShouldReturn: as this:

-(BOOL)textFieldShouldReturn:(UITextField*)textField
{
  NSInteger nextTag = textField.tag + 1;
  // Try to find next responder
  UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
  if (nextResponder) {
    // Found next responder, so set it.
    [nextResponder becomeFirstResponder];
  } else {
    // Not found, so remove keyboard.
    [textField resignFirstResponder];
  }
  return NO; // We do not want UITextField to insert line-breaks.
}

Add some more code, and the assumptions can be ignored as well.

UPDATE:- SWIFT 2.0

func textFieldShouldReturn(textField: UITextField) -> Bool {

let nextTage=textField.tag+1;
// Try to find next responder
let nextResponder=textField.superview?.viewWithTag(nextTage) as UIResponder!

if (nextResponder != nil){
    // Found next responder, so set it.
    nextResponder?.becomeFirstResponder()
}
else
{
    // Not found, so remove keyboard
    textField.resignFirstResponder()
}
return false // We do not want UITextField to insert line-breaks.
}

If the superview of the text field will be a UITableViewCell then next responder will be

let nextResponder=textField.superview?.superview?.superview?.viewWithTag(nextTage) as UIResponder!