Reputation: 45
I want to dismiss keypad when tap on anywhere on screen. For that I used touchbegan
method but this method was not called.
Upvotes: 1
Views: 511
Reputation: 896
You need to assign UITapGestureRecogniser
to view and dismiss keyboard.
In viewdidLoad()
let tap = UITapGestureRecognizer.init(target: self, action: #selector(self.dismissKeybord(_:)))
tap.numberOfTapsRequired = 1
self.view.addGestureRecognizer(tap)
In dismissKeybord
func dismissKeybord(_ sender:UITapGestureRecognizer) {
self.view.endEditing(true)
}
Upvotes: 1
Reputation: 1925
This worked in my case recently. Should work for you too.
(Please note, the parameter true is a value for animated)
class MyViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(endEditing))
tapper.cancelsTouchesInView = false
self.view.addGestureRecognizer(tapGestureRecognizer)
}
func endEditing() {
self.view.endEditing(true)
}
}
Upvotes: 0
Reputation: 3272
Working for me. Showing keyboard on touch to textfields
. Hide on every other touches.
class LoginController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var userLogin: UITextField!
@IBOutlet weak var userPassword: UITextField!
override func viewDidLoad() {
userLogin.delegate = self
userPassword.delegate = self
//For scrolling the view if keyboard on
NotificationCenter.default.addObserver(self, selector: #selector(LoginController.keyboardWillShow),
name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(LoginController.keyboardWillHide),
name: NSNotification.Name.UIKeyboardWillHide, object: nil)
super.viewDidLoad()
}
// OTHER METHODS
var keyBoardAlreadyShowed = false //using this to not let app to scroll view
//if we tapped UITextField and then another UITextField
func keyboardWillShow(notification: NSNotification) {
if !keyBoardAlreadyShowed {
view.frame.origin.y -= 50
keyBoardAlreadyShowed = true
}
}
func keyboardWillHide(notification: NSNotification) {
view.frame.origin.y += 50
keyBoardAlreadyShowed = false
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
}
You need to set delegates
and observers
Upvotes: 0
Reputation: 714
Swift 3 :-
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
Upvotes: 0
Reputation: 955
If your touches are not eaten by other view, then i guess this will work
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if touches.first != nil {
view.endEditing(true)
}
}
Upvotes: 0