键盘在任何地方点击导航项中的搜索控制器

时间:2017-06-25 16:03:38

标签: ios swift uiscrollview uisearchcontroller

我在导航的项目标题视图中有UITeViewController和UISearchController。我希望在表视图中的任何位置点击键盘关闭。如何制作?

到目前为止,这是我的代码:

extension UIViewController {

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

class TableViewController: UITableViewController, UISearchResultsUpdating {

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

        let searchController = UISearchController(searchResultsController: nil)
        searchController.searchResultsUpdater = self

        navigationItem.titleView = searchController.searchBar
    }

    func updateSearchResults(for searchController: UISearchController) {
        //
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 40
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CellID", for: indexPath)
        cell.textLabel?.text = "test1"
        return cell
    }
}

2 个答案:

答案 0 :(得分:1)

您的searchController不在ViewController视图层次结构中,它位于NavigationController视图层次结构中,这就是您的代码无法正常工作的原因。

如果您将代码更改为此

func dismissKeyboard() {
    navigationController?.view.endEditing(true)
}

它会起作用。

答案 1 :(得分:1)

我最终得到了非常好的解决方案,因为TapGestureRecognizer并不是我所需要的。它只在我从屏幕释放手指时触发,而当我滚动时它根本不起作用。所以:

import UIKit
import UIKit.UIGestureRecognizerSubclass

class KeyboardDismissalGestureRecognizer: UIGestureRecognizer {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
        if self.state == .possible {
            UIApplication.shared.keyWindow?.endEditing(true)
        }
    }
}

extension UIViewController {

    func hideKeyboardWhenTouchedAround() {
        let tap = KeyboardDismissalGestureRecognizer(target: self, action: nil)
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }
}

class TableViewController: UITableViewController, UISearchResultsUpdating {

    override func viewDidLoad() {
        super.viewDidLoad()
        hideKeyboardWhenTouchedAround()

        let searchController = UISearchController(searchResultsController: nil)
        searchController.searchResultsUpdater = self
        navigationItem.titleView = searchController.searchBar
    }
//.....
}