【问题标题】:Make keyboard disappear when clicking outside of Search Bar - SWIFT在搜索栏外部单击时使键盘消失 - SWIFT
【发布时间】:2019-01-31 19:02:59
【问题描述】:

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

  1. 添加点击手势识别器
  2. 使用'self.mySearchBar.endEditing(true)'

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

【问题讨论】:

    标签: ios swift searchbar


    【解决方案1】:

    你可以使用这个扩展。

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

    用法。在您的视图控制器中:

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

    【讨论】:

    • 我的类已经是 UIViewController 的子类 - 我不明白扩展位...
    • 这个扩展接近任何控制器。您应该将扩展复制到您想要的任何地方,而不是在任何 viewController 中调用 hideKeyboardWhenTappedAround() 方法。
    猜你喜欢
    • 2017-10-25
    • 1970-01-01
    • 1970-01-01
    • 2015-07-07
    • 2014-09-23
    • 2014-07-21
    • 2018-12-31
    • 2014-07-15
    • 1970-01-01
    相关资源
    最近更新 更多