使用 UISearchController 在 UITableView 中显示搜索结果和键盘覆盖底部 rows/sections

Using UISearchController to display search results and keyboard covers bottom rows/sections in UITableView

有一个 UISearchController,它在 UITableView 中显示搜索结果,UITableView 根据联系人姓名分成按字母顺序排列的部分和相应的行。

当有搜索结果显示比显示键盘的UITableView大几个联系人时,底部的行和部分将被键盘覆盖。

显示筛选后的搜索结果时增加 UITableView 内容高度的最佳方法是什么,以便底部的联系人可以滚动到用户可见,这样它们就不会被覆盖 iOS键盘了?

我正在使用 Swift 3.1 和带有 updateSearchResults 方法的 UISearchResultsUpdating 委托来显示过滤结果。

您需要注意键盘appears/disappears并相应地设置tableView的contentInset

在您的 TableViewController class 中创建两个函数作为键盘事件的响应者:

func keyBoardWillShow(notification: NSNotification) {
    if let keyBoardSize = notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? CGRect {
        let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyBoardSize.height, right: 0)
        self.tableView.contentInset = contentInsets
    }
}

func keyBoardWillHide(notification: NSNotification) {
    self.tableView.contentInset = UIEdgeInsets.zero
}

和register/deregister ViewDidLoaddeinit中的响应者:

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

    // register the responders
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyBoardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyBoardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

}

deinit {
    NotificationCenter.default.removeObserver(self)
}

对于 swift 4.2 及更高版本。 注册观察员。

override func viewDidLoad() {
    super.viewDidLoad()
    // register the responders
    NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillShow), name: UIResponder.keyboardWillShowNotification , object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}

从 iOS 9(和 OS X 10.11)开始,如果您不使用基于块的观察者,则不需要自己删除观察者。系统会为你做这件事,因为它在可能的情况下为观察者使用归零弱引用。

响应事件的函数。

@objc func keyBoardWillShow(notification: NSNotification) {
    if let keyBoardSize = notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? CGRect {
        let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyBoardSize.height, right: 0)
        self.tableView.contentInset = contentInsets
    }
}

@objc func keyBoardWillHide(notification: NSNotification) {
    self.tableView.contentInset = UIEdgeInsets.zero
}