相关文章推荐
眼睛小的盒饭  ·  sql server ...·  6 月前    · 
怕老婆的大熊猫  ·  How does 'SELECT TOP ...·  1 年前    · 
爱喝酒的荔枝  ·  PostgreSQL ...·  1 年前    · 
豪情万千的吐司  ·  chrome google ...·  1 年前    · 
登录

如果我在UIButton中添加UITapGestureRecognizer,则单击事件无效

内容来源于 Stack Overflow,遵循 CC BY-SA 4.0 许可协议进行翻译与使用。IT领域专用引擎提供翻译支持

腾讯云小微IT领域专用引擎提供翻译支持

原文
Stack Overflow用户 修改于2020-07-08
  • 该问题已被编辑
  • 提问者: Stack Overflow用户
  • 提问时间: 2018-01-11 15:53

在我的登录页面上,如果我专注于UITextEdit输入电子邮件和密码,键盘会出现,登录页面向上滚动。如果我触摸键盘外部,我会添加删除键盘的代码。

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

在我的viewDidLoad()函数中,我像这样添加了它。

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

它工作得很好,但是如果我在键盘仍然打开的时候单击登录按钮,辞退键盘()函数可以工作,但是btnClick函数不能工作。

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

我该如何解决这个问题?

浏览 8 关注 0 得票数 3
  • 得票数为Stack Overflow原文数据
原文

4 个回答

回答于2018-01-11
得票数 2

我使用以下代码对其进行了测试:

import UIKit
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)
class ViewController: UIViewController {
    fileprivate let textField = UITextField(frame: CGRect(x: 0, y: 0, width: 400, height: 50))
    fileprivate let button = UIButton(frame: CGRect(x: 20, y: 200, width: 150, height: 50))
    override func loadView() {
        super.loadView()
        view.addSubview(textField)
        textField.backgroundColor = .lightGray
        view.addSubview(button)
        button.setTitle("Press me", for: .normal)
        button.setTitleColor(UIColor.blue, for: .normal)
        button.addTarget(self, action: #selector(a), for: .touchUpInside)
        hideKeyboardWhenTappedAround()