Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift UITextFieldShouldReturn Return Key Tap

(iOS8, Xcode6, Swift) Using Swift, how do I capture a tap on the "Return" button?

The doc at the following link specifies using the textFieldShouldReturn method:

// Swift
@optional func textFieldShouldReturn(_ textField: UITextField!) -> Bool

Where I'm hung up is in the "_ textField" part. I've created the text field using Storyboard. How do I capture notifications for this specific text field? Do I need to create a new class and set it as a delegate for this text field? Do I assign the text filed a name, and then somehow hook into it?

https://developer.apple.com/documentation/uikit/uitextfielddelegate/1619603-textfieldshouldreturn

like image 608
kmiklas Avatar asked Jun 10 '14 21:06

kmiklas


3 Answers

class ViewController: UIViewController,UITextFieldDelegate //set delegate to class

@IBOutlet var txtValue: UITextField //create a textfile variable

override func viewDidLoad() {
   super.viewDidLoad() 
   txtValue.delegate = self //set delegate to textfile 
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {   //delegate method
   textField.resignFirstResponder()
   return true
}
like image 64
jayesh kavathiya Avatar answered Oct 23 '22 01:10

jayesh kavathiya


Implement this function

func textFieldShouldReturn(_ textField: UITextField) -> Bool {   //delegate method
   textField.resignFirstResponder()
   return true
}

And for delegate you can set using the Utilities pane / Connections Inspector / delegate and then drag to ViewController (yellow button in the storyboard)

Then you do not need to set the delegate programmatically for every text field

like image 25
sijones Avatar answered Oct 22 '22 23:10

sijones


In Swift 4.2 and Xcode 10.1

//UITextField delegate method
func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    if textField == TF1 {
        textField.resignFirstResponder()//
        TF2.becomeFirstResponder()//TF2 will respond immediately after TF1 resign.
    } else if textField == TF2  {
        textField.resignFirstResponder()
        TF3.becomeFirstResponder()//TF3 will respond first
    } else if textField == TF3 {
        textField.resignFirstResponder()
    }
    return true
}
like image 6
Naresh Avatar answered Oct 23 '22 00:10

Naresh