【问题标题】:Dismiss keyboard when uitableview cell is selected and using UISearchController选择 uitableview 单元格并使用 UISearchController 时关闭键盘
【发布时间】:2016-06-08 19:36:57
【问题描述】:

所以我有一个应用程序,它基本上是一个使用 UITableViewController 和 UISearchController 显示的电影搜索应用程序。

我有一个单元格,点击后会加载更多结果。但是当我点击它时,我也希望键盘消失。所以在tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) 方法中,我假设我必须调用resignFirstResponder()。问题是它不起作用。我已经尝试了一切,但没有什么能让键盘消失。我认为这是因为键盘是 UISearchBar 的一部分,我应该调用searchBar.resignFirstResponder()。问题是我无法从 UITableViewController 类访问 searchBar。

这是我所拥有的,这些都不起作用:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        //Remove Keyboard
            self.resignFirstResponder()
            self.view.resignFirstResponder()
            self.view.endEditing(true)
            self.tableView.endEditing(true)
            self.navigationController?.view.endEditing(true)
            self.navigationController?.resignFirstResponder()

        //Do a bunch of other stuff..
}

【问题讨论】:

    标签: ios swift uitableview resignfirstresponder


    【解决方案1】:

    如果您知道searchBar 是第一响应者,那么:

    1. 将对searchBar 的引用传递给UITableViewController
    2. 使用 KVC:发布一条通知,说明您正在加载更多结果并且键盘应该被隐藏,并在您的 UISeachController 中收听该通知。

    【讨论】:

    • 我试图避免这种情况。这样做不是效率低下吗?不过,它奏效了。谢谢!
    • 为什么会低效?委托是最好的解决方案,但如果您不想传递引用,也可以使用通知。
    • 当我将tableview 的“searchBar”变量设置为SearchController.SearchBar 时,我是通过引用分配的吗?如果是这样,那么这将是最有效和最整洁的方式。
    【解决方案2】:
    [[UIApplication sharedApplication]sendAction:@selector(resignFirstResponder)
                                                     to:nil
                                                   from:nil
                                               forEvent:nil];
    

    【讨论】:

      猜你喜欢
      • 2016-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-16
      • 2020-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多