Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 490
phx Avatar asked Aug 28 '09 15:08

phx


People also ask

What is a UITextField?

An object that displays an editable text area in your interface.

What is TextField in Swift?

A TextField is a type of control that shows an editable text interface. In SwiftUI, a TextField typically requires a placeholder text which acts similar to a hint, and a State variable that will accept the input from the user (which is usually a Text value).


1 Answers

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.

Swift 4.0

 func textFieldShouldReturn(_ textField: UITextField) -> Bool {     let nextTag = textField.tag + 1     // Try to find next responder     let nextResponder = textField.superview?.viewWithTag(nextTag) as UIResponder!      if nextResponder != nil {         // Found next responder, so set it         nextResponder?.becomeFirstResponder()     } else {         // Not found, so remove keyboard         textField.resignFirstResponder()     }      return false } 

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

let nextResponder = textField.superview?.superview?.superview?.viewWithTag(nextTag) as UIResponder! 
like image 108
PeyloW Avatar answered Sep 28 '22 05:09

PeyloW