Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching between Text fields on pressing return key in Swift

I'm designing an iOS app and I want that when the return key is pressed in my iPhone it directs me to the next following text field.

I have found a couple of similar questions, with excellent answers around but they all just happen to be in Objective-C and I'm looking for Swift code, now this is what I have up until now:

func textFieldShouldReturn(emaillabel: UITextField) -> Bool{     return true } 

It's placed in the file that's connected and controller to the UIView that contains the text fields, but I'm not sure if thats the right place.

Okay, so I tried this out and got this error:
//could not find an overload for '!=' that accepts the supplied arguments

func textFieldShouldReturn(textField: UITextField) -> Bool {     let nextTag: NSInteger = textField.tag + 1     // Try to find next responder     let nextResponder: UIResponder = textField.superview!.viewWithTag(nextTag)!     if (nextResponder != nil) {         // could not find an overload for '!=' that accepts the supplied arguments          // 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. } 
like image 799
lucas rodriguez Avatar asked Aug 01 '15 22:08

lucas rodriguez


People also ask

How do you dismiss a keyboard when tapping outside Swift?

Via Tap Gesture This is the quickest way to implement keyboard dismissal. Just set a Tap gesture on the main View and hook that gesture with a function which calls view. endEditing . Causes the view (or one of its embedded text fields) to resign the first responder status.


1 Answers

Make sure your UITextField delegates are set and the tags are incremented properly. This can also be done through the Interface Builder.

Here's a link to an Obj-C post I found: How to navigate through textfields (Next / Done Buttons)

class ViewController: UIViewController,UITextFieldDelegate {    // Link each UITextField (Not necessary if delegate and tag are set in Interface Builder)    @IBOutlet weak var someTextField: UITextField!     override func viewDidLoad() {       super.viewDidLoad()       // Do the next two lines for each UITextField here or in the Interface Builder       someTextField.delegate = self       someTextField.tag = 0 //Increment accordingly    }     func textFieldShouldReturn(_ textField: UITextField) -> Bool {       // Try to find next responder       if let nextField = textField.superview?.viewWithTag(textField.tag + 1) as? UITextField {          nextField.becomeFirstResponder()       } else {          // Not found, so remove keyboard.          textField.resignFirstResponder()       }       // Do not add a line break       return false    } } 
like image 53
Caleb Avatar answered Oct 05 '22 22:10

Caleb