Ios 如何在uitextfield或button外部点击退出键盘

Ios 如何在uitextfield或button外部点击退出键盘,ios,swift,xcode,Ios,Swift,Xcode,我需要能够在未点击uitextfield或未点击show/hide password(显示/隐藏密码)按钮时点击键盘 我以前使用过这段代码: extension UIViewController { func hideKeyboardWhenTappedAround() { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewContr

我需要能够在未点击uitextfield或未点击show/hide password(显示/隐藏密码)按钮时点击键盘

我以前使用过这段代码:

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)
    }
}
但问题是,即使在单击“显示/隐藏密码眼”图标时,它也会从键盘外单击。我用于显示/隐藏图标的代码如下:

extension UITextField {
    func showhidepasswordbutton(image: UIImage = UIImage(systemName: "eye.slash")!) {
        let button = UIButton(type: .custom)
        button.setImage(image, for: .normal)
        button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -16, bottom: 0, right: 0)
        button.frame = CGRect(x: CGFloat(self.frame.size.width - 25), y: CGFloat(5), width: CGFloat(25), height: CGFloat(25))
        button.addTarget(self, action: #selector(self.refreshforshowhide), for: .touchUpInside)
        button.tintColor = .darkGray
        self.rightView = button
        self.rightViewMode = .always
        
        
    }
    
    @IBAction func refreshforshowhide(_ sender: Any) {
        print("ok")
        
        if self.isSecureTextEntry == true {
            self.togglePasswordVisibility()
            showhidepasswordbutton(image: UIImage(systemName: "eye")!)
            
        } else if self.isSecureTextEntry == false {
            self.togglePasswordVisibility()
            showhidepasswordbutton(image: UIImage(systemName: "eye.slash")!)
            
        }
        
    }
    func togglePasswordVisibility() {
        let temptext = self.text
        isSecureTextEntry.toggle()
        self.text = ""
        self.text = temptext
        
    }
    
}

很抱歉代码太乱,刚刚编写了显示/隐藏密码代码。

您可以使用
UIgestureRecognitizerDelegate
中的
gestureRecognitizer(:,shouldReceive:)
方法排除对子视图的点击

extension UIViewController: UIGestureRecognizerDelegate {
    func hideKeyboardWhenTappedAround() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
        tap.cancelsTouchesInView = false
        tap.delegate = self
        view.addGestureRecognizer(tap)
    }

    @objc func dismissKeyboard() {
        view.endEditing(true)
    }

    public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        touch.view?.isDescendant(of: view) == false // will return false if touch was received by a subview
    }
}
更新:您可以使用
touch.view==view
而不是
touch.view?.isDescendat(of:view)==false