I have UITextField and UIButton in my application.
To hide system keyboard which is shown when UITextField is clicked, I added UITapGestureRecognizer to my view.
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(didTap(_:)))
view.addGestureRecognizer(tapGesture)
}
@objc func didTap(_ recognizer: UIGestureRecognizer) {
view.endEditing(true)
}
@IBAction func onClickedButton(_ sender: Any) {
print("aaa")
}
This code worked very well when I touched outside of my button.
However, when I clicked the button which has IBAction(onClickedButton), the keyboard did not disappear and only the message "aaa" printed in output console.
What I want to do is to hide keyboard and invoke IBAction at the same time. In other words, I want to invoke Tap gesture and IBAction at the same time, when I clicked my button.
How can I acheive this?
CodePudding user response:
You can just add view.endEditing(true)
to your onClickedButton
.
CodePudding user response:
try this
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(didTap(_:)))
view.addGestureRecognizer(tapGesture)
}
@objc func didTap(_ recognizer: UIGestureRecognizer) {
view.endEditing(true)
}
@IBAction func onClickedButton(_ sender: Any) {
print("aaa")
view.endEditing(true)
}
}
CodePudding user response:
I found the solution.
Just setting
tapGesture.cancelsTouchesInView = false
can acheive this.
By doing like this, tapGesture hides keyboard and after that, passes touch event to the UIButton.