Why is the textFieldShouldReturn function not being called?
The rest of this answer is still very useful, and I'll leave it there as it can potentially help other askers... but here, I missed the obvious problem with this specific example...
We're not calling resignFirstResponder
on the text field. We're calling it on the view controller. We need to call it on the text field, so modify your code to look like this:
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
A UITextField
will only call the textFieldShouldReturn
property on the object which is its delegate.
We can fix this programmatically by adding a viewDidLoad
method to set that:
override func viewDidLoad() {
super.viewDidLoad()
self.textField.delegate = self
}
But we can also set this up via the storyboard at build time.
Right click on the textfield to check and see whether or not the delegate has been set:
If that circle next to delegate
is unfilled, we haven't set the delegate for our UITextField
yet.
To set the delegate, hover over this circle. It will change to a plus sign. Now click and drag to the view controller that you want to delegate the text field (the view controller the text field is part of).
When you've appropriately hooked the view controller up as a delegate, this menu should look like this:
If using Swift 3+, you have to add an underscore before the first property. Like:
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
This is also very well documented in the Apple Documentation. https://developer.apple.com/documentation/uikit/uitextfielddelegate/1619603-textfieldshouldreturn
I'm enrolled in a Swift 4 Udemy course, and the instructor said to add the UITextFieldDelegate class for the ViewController in addition to Cntrl - dragging from the textField to the ViewController button and selecting delegate.
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}