我正在使用UISearchController搜索栏作为模态视图控制器中导航栏的标题视图。我将其设置为:
var searchController: UISearchController!
override func viewDidLoad() {
super.viewDidLoad()
searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false
searchController.hidesNavigationBarDuringPresentation = false
searchController.searchBar.showsCancelButton = false
navigationItem.titleView = searchController.searchBar
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// for whatever reason, it's necessary to make the search controller first responder
// on the main queue. reference: https://stackoverflow.com/a/41657181/2335677
DispatchQueue.main.async {
self.searchController.searchBar.becomeFirstResponder()
}
}
[一切正常,dismiss()
除外,searchController.isActive = true
时滑动并关闭模式不起作用
我可以先将其设置为非活动状态,以解决dismiss()问题:
@IBAction private func done(_ sender: UIBarButtonItem) {
searchController.isActive = false
dismiss(animated: true)
}
但是如上所述,我无法向下滑动以关闭视图控制器。而且我想不出解决方法。我尝试过:
UIAdaptivePresentationControllerDelegate
方法并尝试在其中一些方法中设置searchController.isActive = false
(无效)definesPresentationContext = true
(没有影响)还有其他想法吗?
[如果您想要一个单独的屏幕用于搜索,并且只需要像我一样在导航栏标题中需要一个搜索栏,那么使用UISearchBar会更容易:
override func viewDidLoad() {
super.viewDidLoad()
searchBar = UISearchBar()
searchBar.showsCancelButton = false
navigationItem.titleView = searchBar
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
searchBar.becomeFirstResponder()
}
外观相同,由于UISearchController并未劫持您的视图控制器,因此您现在获得了所有默认行为。