Reputation: 29
Below is my code for hiding keyboard on pressing return key, But it's not working.
class AddHall: UIViewController,UITextFieldDelegate {
@IBOutlet weak var hallname: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
hallname.delegate = self
}
func textFieldShouldReturn(hallname : UITextField!) -> Bool {
hallname.resignFirstResponder()
return true
}
}
Upvotes: 1
Views: 4569
Reputation: 11
None of these worked alone for me. Rather:
class ViewController: UIViewController, UITextFieldDelegate
textField.delegate = self
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
textField.resignFirstResponder()
return false
}
Upvotes: -1
Reputation:
Implement correct UITextField Delegate method.
replace
func textFieldShouldReturn(hallname : UITextField!) -> Bool {
hallname.resignFirstResponder()
return true
}
with
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
Upvotes: 4
Reputation: 10209
The delegate method textFieldShouldReturn
is used to specify if the text field is allowed to lose the focus - it will only be called just before the UITextField is about to lose its focus. You should only do some checks her, but not dismiss anything.
What you seek is to react on the return key, and then dismiss the keyboard. This is done by connecting the DidEndOnExit
action (be aware: there are a lot of other events with similar names, you'll have to exactly use this one), and there resign the first responder.
You can then just remove textFieldShouldReturn
(unless you do some additional checks here and not simply return true
).
Upvotes: 1
Reputation: 2923
You have to use correct function name for TextField Delegate
Use this:
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
Upvotes: 0
Reputation: 339
change your code like this. You are not using correct delegate method.
func textFieldShouldReturn(textField : UITextField!) -> Bool {
textField.resignFirstResponder()
return true
}
Upvotes: 0