【问题标题】:Dismiss Keyboard And Allow Button Gesture Recognizers Swift iOS关闭键盘并允许按钮手势识别器 Swift iOS
【发布时间】:2021-07-07 01:46:57
【问题描述】:

当用户点击 TextView 之外的屏幕上的任意位置时,我正在使用此代码隐藏键盘:

 override func viewDidLoad() {
        super.viewDidLoad()
        //Looks for single or multiple taps.
        let tap = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))
        tap.delegate = self
        //Uncomment the line below if you want the tap not not interfere and cancel other interactions.
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }
    
    //Calls this function when the tap is recognized.
    @objc func dismissKeyboard() {
        //Causes the view (or one of its embedded text fields) to resign the first responder status.
        view.endEditing(true)
    }
    
    public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        if touch.view is UIButton {
            return false
        }
        return true
    }

问题是我在这个视图中也有一个UIButton - 当我点击按钮时,不会调用按钮的手势识别器功能。相反,dismissKeyboard 被调用。我已经尝试过使用 tap.cancelsTouchesInView = falseshouldReceive 方法的建议,但是它们都不起作用——在shouldReceive 方法中,当我点击按钮时,touch.view 的类是UIView

有谁知道如何让用户在点击屏幕上的任意位置时隐藏键盘,同时还允许执行按钮操作处理程序?

【问题讨论】:

    标签: ios swift uibutton uitextfield uigesturerecognizer


    【解决方案1】:

    我使用以下代码解决了这个问题:

    1. 我检测到用户触摸的位置

    2. 我检查触摸是否在我的UIView 中的两个按钮的框架中

    3. 如果是这样,我手动调用按钮处理程序并从方法中返回 false

      public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
       if let view = self.view as? MyViewControllersView {
           let location = touch.location(in: self.view)
           if view.saveButton.frame.contains(location) {
               view.saveHit()
               return false
           } else if view.scanButton.frame.contains(location) {
               view.scanHit()
               return false
           }
       }
       return true
      }
      

    【讨论】:

      【解决方案2】:

      它对我有用,请查看

      //MARK:- View Lyfe cycle
      override func viewDidLoad() {
          super.viewDidLoad()
           IQKeyboardManager.shared().isEnableAutoToolbar = false
      //        IQKeyboardManager.shared().disabledToolbarClasses = self
          IQKeyboardManager.shared().isEnabled = false
          self.keyboardWillShowAndHide()
          initializeHideKeyboard()
       }
      
      //MARK:- KayBoard Handling...
      //MARK:- Init Hide KeyBoard...
      func initializeHideKeyboard(){
          //Declare a Tap Gesture Recognizer which will trigger our dismissMyKeyboard() function
          let tap: UITapGestureRecognizer = UITapGestureRecognizer(
              target: self,
              action: #selector(dismissMyKeyboard))
          //Add this tap gesture recognizer to the parent view
          view.addGestureRecognizer(tap)
      }
      //MARK:- Dismissing Keyboard...
      @objc func dismissMyKeyboard(){
          //endEditing causes the view (or one of its embedded text fields) to resign the first responder status.
          //In short- Dismiss the active keyboard.
          view.endEditing(true)
      }
      //MARK:- Kayboard Hide and Show...
      func keyboardWillShowAndHide(){
          NotificationCenter.default.addObserver(
              self,
              selector: #selector(keyboardWillShow),
              name: UIResponder.keyboardWillShowNotification,
              object: nil
          )
          NotificationCenter.default.addObserver(
              self,
              selector: #selector(keyboarddidHide),
              name: UIResponder.keyboardWillHideNotification,
              object: nil
          )
          
      }
      //MARK:- KeyBoard Will Show
      @objc func keyboardWillShow(_ notification: Notification) {
          self.arrConversationList.count
          if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
              let keyboardRectangle = keyboardFrame.cgRectValue
              let keyboardHeight = keyboardRectangle.height
              self.ChatBottomConstraint.constant = keyboardHeight - self.bottomLayoutGuide.length
              DispatchQueue.main.asyncAfter(deadline: .now()+0.1, execute: {
                  if  self.arrConversationList.count > 0 {
                      let indexPath = NSIndexPath(row: self.arrConversationList.count-1, section: 0)
                      self.ConversationTblref.scrollToRow(at: indexPath as IndexPath, at: .bottom, animated: true)
                  }
              })
              self.tableviewbottomconstraintref.constant = 0
              ConversationTblref.reloadData()
          }
      }
      //MARK:- KeyBoard Will Hide
      @objc func keyboarddidHide(_ notification: Notification) {
          self.tableviewbottomconstraintref.constant = 0
          self.ChatBottomConstraint.constant = 0
          ConversationTblref.reloadData()
      }
      
      //MARK:- View Disappear for handleing kayboard...
      override func viewWillDisappear(_ animated: Bool) {
          super.viewWillDisappear(true)
          IQKeyboardManager.shared().isEnableAutoToolbar = true
          IQKeyboardManager.shared().isEnabled = true
           NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
          NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
          
      
      }
      
      override func viewDidDisappear(_ animated: Bool) {
         
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-05-25
        • 1970-01-01
        • 2011-06-17
        • 1970-01-01
        • 2016-12-26
        • 1970-01-01
        相关资源
        最近更新 更多