Son
Son

Reputation: 147

UITapGestureRecognizer is not invoked when I clicked button with IBAction

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?

Upvotes: 2

Views: 444

Answers (3)

Son
Son

Reputation: 147

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.

Upvotes: 3

bdeviOS
bdeviOS

Reputation: 563

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)
    }
}

Upvotes: 0

user17353495
user17353495

Reputation:

You can just add view.endEditing(true) to your onClickedButton.

Upvotes: 0

Related Questions