Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
526 views
in Technique[技术] by (71.8m points)

ios - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I actually solved it a little different way (I had the same problem on my login screen). I just moved the dismissing/animating of the keyboard into an async block with a tiny delay, because it seemed like with the tap recognizer, it was picking up the touch down, but not the touch up inside the button, likely because the screen had already started to animate the dismissal of the keyboard.

@objc func dismissKeyboard() {
    DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) {
        self.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)
        })
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...