ios - 单击按钮会隐藏键盘,并且键盘弹起时不会执行操作

标签 ios swift

我使用以下代码在单击 UITextField 时抬起键盘。

NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardDidShow, object: nil)

NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

self.hideKeyboardWhenTappedAround()

这是我正在使用的扩展。

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

我遇到的问题是,当键盘打开时,它会使一个主按钮(搜索按钮)无法单击。如果我单击此按钮,它只会降低键盘,然后我必须再次单击它。

如何解决这个问题?

最佳答案

为了解决这个问题,我在一个项目中所做的就是监听手势识别器。如果被操作的元素是一个按钮,我不会执行该操作。

首先,分配您的 tapGesture 识别器的委托(delegate)

    func hideKeyboardWhenTappedAround() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
        tap.cancelsTouchesInView = false
        tap.delegate = self // assign the delegate to the viewcontroller/who ever you assigned to conform to the UIGestureRecognizerDelegate
        view.addGestureRecognizer(tap)
    }


遵循UIGestureRecognizerDelegate并使用函数shouldReceive touch来决定采取什么操作。为了解决您的问题,如果用户点击按钮,我们不会执行该手势。


extension UIViewController: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        return !(touch.view is UIButton)
    }
}

需要注意的是,如果您确实执行按钮操作而不是手势,则需要在按钮执行处理后实现/调用关闭键盘方法。

关于ios - 单击按钮会隐藏键盘,并且键盘弹起时不会执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61839159/

相关文章:

ios - 调用 'becomeFirstResponder()' 的结果是 UITableView 中未使用的 UITextField

ios - swift : Save & Show selected indexPath in static Table View

ios - 在 realm 中保存数据模型对象数组只保存 1 个属性,其余属性我在 realm studio 中看不到

ios - 具有最大长度的 UITextField 自动完成

iphone - UITabBar 标准图标位置

ios - AFHTTPSessionManager 忽略 HTTPMaximumConnectionsPerHost

ios - 状态栏中的事件指示器始终隐藏

ios - UIBarButtonItem 改变播放/暂停按钮的图像

android - 如何生成像提供的图像中的那样的 ClipPath

ios - "Allow Non-modular includes in Framework Modules"设置到底是什么?