在我的应用中,我需要创建一个搜索建议界面——与 Google 搜索非常相似(它会在您在搜索字段中键入时开始显示建议)。
我用导航栏中带有搜索栏的 UISearchController
做到了,设置如下:
// setup search controller
searchController = UISearchController(searchResultsController: searchSuggestionsController)
self.searchController.searchResultsUpdater = searchSuggestionsController
self.searchController.hidesNavigationBarDuringPresentation = false
self.navigationItem.titleView = self.searchController.searchBar
// ISSUE!! definesPresentationContext needs to be false or I can't push this
// controller multiple times on the navigation stack
self.definesPresentationContext = true
虽然第一次将搜索 Controller 推送到导航堆栈时它工作正常,但它不会让搜索栏在第二次推送时获得焦点,如下所示
但如果我将其设置为 false:一旦我开始在搜索栏中输入内容,导航栏(连同搜索栏)就会消失。这是预期的行为,因为(因为 definesPresentationContext = false
)UISearchController
现在试图在 UINavigationController
的 View 之上显示它的 View ,因为如下所示:
有没有办法通过 UISearchController 实现这一点?如果没有,关于我应该如何为此创建自定义控件的任何指示? (动画中显示的最小应用程序代码可以是 downloaded here )
不可能像这样使用 UISearchController。众所周知,UISearchBar 和 UINavigationBar 不能很好地协同工作。我决定做的是,每次用户点击搜索按钮时,我都会检查我的导航 Controller 的 childViewControllers
数组,如果我在那里找到 SearchViewController
的实例,我弹出回到它。否则我推它。
// This function lives inside a UINavigationController subclass and is called whenever I need to display the search controller
func search() {
if let _ = self.topViewController as? SearchViewController {
return
}
var existingSearchController: SearchViewController? = nil
for childController in self.childViewControllers {
if let searchController = childController as? SearchViewController {
existingSearchController = searchController
}
}
if let searchController = existingSearchController {
self.popToViewController(searchController, animated: true)
return
}
self.performSegueWithIdentifier(StoryboardConstants.SegueShowSearchController, sender: nil)
}
当然,正确的解决方法是自定义控件,但我们现阶段没有时间编写自定义控件。
Tôi là một lập trình viên xuất sắc, rất giỏi!