代码之家  ›  专栏  ›  技术社区  ›  johnDoe

在搜索栏外单击时使键盘消失-SWIFT

  •  1
  • johnDoe  · 技术社区  · 7 年前

    我有一个UIViewController,我嵌入了一个搜索栏和一个集合视图。当我按下搜索栏时,键盘出现。我想隐藏这个键盘,如果用户决定改变主意,点击屏幕上除搜索栏以外的任何地方。我尝试过以下方法,但没有成功:

    1. 添加轻敲手势识别器
    2. class CollectionViewFolder: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate ,UICollectionViewDelegateFlowLayout, UISearchBarDelegate{
      
      /*** OUTLETS ***/
      @IBOutlet weak var mySearchBar: UISearchBar!
      
      
      // 1. I have tried adding a Tap Gesture Recognizer
      // TAP ON SCREEN LISTENER
      @IBAction func tapOnScreen(_ sender: UITapGestureRecognizer) {
         print("tap tap ...")
         self.mySearchBar.resignFirstResponder()
      }
      
      
      
      // 2.  Added the following to the viewDidLoad:
      override func viewDidLoad() {
         super.viewDidLoad()
      
         self.mySearchBar.endEditing(true)
       }
      
      }
      

    enter image description here

    1 回复  |  直到 7 年前
        1
  •  4
  •   Alex Kolovatov    7 年前

    你可以用这个分机。

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

    用法。在viewController中:

    override func viewDidLoad() {
        super.viewDidLoad()
    
        hideKeyboardWhenTappedAround()
    }