我有一个带搜索栏 (UISearchController) 的导航栏 当我点击左侧按钮图标时,通过将其分配给navigationItem来显示此搜索控制器,如下所示:
if navigationItem.searchController != nil {
navigationItem.searchController = nil
navigationController?.view.setNeedsLayout()
navigationController?.view.layoutIfNeeded()
} else {
navigationItem.searchController = searchController
navigationController?.view.setNeedsLayout()
navigationController?.view.layoutIfNeeded()
searchController.searchBar.becomeFirstResponder()
}
它能够使用,但如果在取消按钮触摸后尝试隐藏搜索栏,则会导致视图控制器被解除和黑屏出现(没有视图控制器)
extension SearchableMenuViewController : UISearchBarDelegate {
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
guard #available(iOS 11.0, *) else { return }
guard !isAlwaysVisible else { return }
if #available(iOS 13.0, *) {
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
self.navigationItem.searchController = nil
self.navigationController?.view.setNeedsLayout()
self.navigationController?.view.layoutIfNeeded()
}
} else {
navigationItem.searchController = nil
navigationController?.view.setNeedsLayout()
navigationController?.view.layoutIfNeeded()
}
}
我尝试添加延迟,因为如果不从navigationItem中移除此searchcontroller,则它会以标题+搜索控制器的扩展导航栏的形式进行动画处理,然后点击搜索图标可以正确隐藏搜索控制器。所以问题在于,我认为在将搜索控制器动画到扩展导航栏时移除搜索控制器。