Reputation: 16212
In my storyboard
I have a basic view, with a login field. In the storyboard the checkbox for Enable user interaction
is checked, and I am also settings this through the code.
Below is the code I'm using for this:
class LoginViewController : UIViewController {
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var passwordField: UITextField!
override func viewDidLoad() {
super.viewDidLoad();
let closeKeyboardGesture = UITapGestureRecognizer(target: self, action: "dismissKeyboard");
self.view.userInteractionEnabled = true
self.view.addGestureRecognizer(closeKeyboardGesture);
}
private func dismissKeyboard() {
print("Called")
if passwordField.selected {
passwordField.resignFirstResponder()
}
if emailField.selected {
emailField.resignFirstResponder()
}
}
}
As you can see it's fairly straightforward, however the dismissKeyboard function is never called. What bothers me is I'm using these gestures elsewhere in my application and they're working fine.
Upvotes: 0
Views: 65
Reputation: 871
func dismissKeyboard() {
view.endEditing(true)
}
This will do the trick.
Upvotes: 1
Reputation: 38833
That´s because you have your dismissKeyboard
function marked as private
. If you are calling a method from a selector and it is private they cannot be called because the method is called from outside.
So remove private
from dismissKeyboard
and it will work.
Update
If you change the above it will work, what´s not working for you right now is the resignFirstResponder
You don´t need to the if-checks since you always want to hide the keyboard when you active the closeKeyboardGesture
, so it´s enough to only call self.view.endEditing(true)
. I have created a sample project for you that has a working example. You can download it from here.
Upvotes: 1