Ok, I think for a novice things might be a bit confusing. I think the correct answer is a mix of all the above, at least in Swift4.
Either create an extension or use the ViewController in which you'd like to use this but make sure to implement UITextFieldDelegate. For reusability's sake I found it easier to use an extension:
extension UIViewController : UITextFieldDelegate {
...
}
but the alternative works as well:
class MyViewController: UIViewController {
...
}
Add the method textFieldShouldReturn (depending on your previous option, either in the extension or in your ViewController)
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return textField.endEditing(false)
}
In your viewDidLoad method, set the textfield's delegate to self
@IBOutlet weak var myTextField: UITextField!
...
override func viewDidLoad() {
..
myTextField.delegte = self;
..
}
That should be all. Now, when you press return
the textFieldShouldReturn
should be called.