Swift UITextFieldShouldReturn Return Key Tap

kmiklas picture kmiklas · Jun 10, 2014 · Viewed 66.2k times · Source

(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

Answer

jayesh kavathiya picture jayesh kavathiya · Jul 7, 2014
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
}