UISearchController 需要额外点击才能成为第一响应者

UISearchController Needs an extra tap to become first responder

我将我的应用程序从 UISearchBar 切换到 UISearchController 一屏。这是一个表视图控制器。根据设计,我最初不应该将搜索栏保持在 UI 上,除非它被激活(通常将搜索栏保持为 'tableHeaderView' 是一种常见的做法)。问题是,我有一个搜索按钮,当点击时 'search bar' 应该被激活并成为第一响应者。

点击取消按钮时,应将其从 UI 中删除。但是,当我点击导航栏上的 'Search Bar Button' 时,UISearchController 被激活,提供暗淡的背景,但键盘没有出现。我需要在搜索栏上再点击一次才能将键盘调到 UI。

这是我的搜索栏按钮操作:

@IBAction func onTapSearch(_ sender: AnyObject) {
    self.view.addSubview(searchController.searchBar)
    searchController.isActive = true
    searchController.becomeFirstResponder()
    isSearchActive = true
    self.navigationController?.setToolbarHidden(true, animated: false)
}

我正在 viewDidLoad 方法中配置 UISearchController。让我知道该部分代码是否是您想要查看的任何一个,但它是常用代码。我确认我没有在任何地方调用 resignFirstResponder() 方法。

试试这个,

只需替换这一行,

searchController.becomeFirstResponder()

有了下面这个,

searchController.searchBar.becomeFirstResponder()

编辑,

func didPresentSearchController(_ searchController1: UISearchController) {
    searchController1.searchBar.becomeFirstResponder()
}

实现这个委托方法并尝试。