我在导航栏中使用UISearchController
实现了搜索栏。还有一个表视图,其顶部约束设置在导航栏的底部。
期望的行为::当按下取消按钮时,搜索栏被隐藏,表格视图的顶部约束返回到删除搜索栏之前的状态(请参见屏幕快照帖子末尾的#1 )
当前行为::按下“取消”按钮时,搜索栏消失了,但tableView的顶部约束没有响应变化(请参阅屏幕#3 )
此问题的可能解决方案是每当单击“取消”按钮时手动更新约束。但是,我找不到从UISearchBarDelegate
方法searchBarCancelButtonClicked
代码段:
class ViewController: UIViewController {
let searchController = UISearchController(searchResultsController: nil)
override func viewDidLoad() {
super.viewDidLoad()
searchController.searchBar.delegate = self
/* Adding search button to the navbar */
/* setting tableView constraints */
/* tableView delegate/datasource methods, etc... */
}
@objc func searchButtonTapped(_ sender: UIBarButtonItem) {
setup()
navigationItem.searchController = searchController
}
func setup() {
searchController.hidesNavigationBarDuringPresentation = false
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.sizeToFit()
}
}
extension UISearchBarDelegate {
public func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
navigationItem.searchController = nil
/* Cannot access tableview constraints from here because extension is outside of the class */
}
}
答案 0 :(得分:1)
添加如下一行代码:
func searchBarCancelButtonClicked(_ searchBar: UISearchBar){
self.navigationItem.searchController = nil
self.view.setNeedsLayout()
/* Cannot access tableview constraints from here because extension is outside of the class */
}
答案 1 :(得分:1)
(是的,这是对的)
func searchBarCancelButtonClicked(_ searchBar: UISearchBar){
self.navigationItem.searchController = nil
self.view.setNeedsLayout()
/* Cannot access tableview constraints from here because extension is outside of the class */
}
答案 2 :(得分:0)
尝试像这样更新导航控制器内的视图:
func searchBarCancelButtonClicked(_ searchBar: UISearchBar){
navigationItem.searchController = nil // or searchController
navigationController?.view.setNeedsLayout() // invalidate current layout
navigationController?.view.layoutIfNeeded() // force update layout
}