Search code examples
iosswiftuibuttonuitapgesturerecognizer

UIButton Click Event not working if I add UITapGestureRecognizer in swift


On my login page, if I focus to UITextEdit for entering email and password, keyboard appears and login page scroll up. And I add this code for remove keyboard if I touch outside of keyboard.

extension UIViewController {
    func hideKeyboardWhenTappedAround() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }
    
    @objc func dismissKeyboard() {
        view.endEditing(true)
        UIView.animate(withDuration: 0.3, animations: {
            self.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
        })
    }
}

And on my viewDidLoad() function, I added it like this.

override func viewDidLoad() 
{
        super.viewDidLoad()
        //TODO
        self.hideKeyboardWhenTappedAround()
       ...
}

It works well, But If I click login button when keyboard is still opening, dismisskeyboard() function works but btnClick function doesn't work.

@IBAction func LoginBtnClick(_ sender: Any) 
{
        print("loginBtn")
        //...
}

How can I solve this problem?


Solution

  • Don't add the gesture to main viewController's view add a full screen subview below UIButton and add the gesture to it