我在导航栏中使用UISearchController实现了一个搜索栏。还有一个表视图,其顶部约束设置为导航栏的底部。
想要的行为:当按下“取消”按钮时,搜索栏被隐藏,表视图的顶部约束返回到删除搜索栏之前的状态(见文章末尾的屏幕截图#1 )。
当前行为:当按下“取消”按钮时,搜索栏消失,但tableView的顶部约束没有改变(参见屏幕截图#3)
解决此问题的一个可能的解决方案是每当单击“取消”按钮时手动更新约束。但是,我找不到从UISearchBarDelegate方法searchBarCancelButtonClicked访问tableView的约束的方法
代码片段:
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 */
}
}在按下搜索按钮之前。

在按下“取消”按钮之前。

在按下“取消”按钮后。

发布于 2018-09-13 18:04:48
(是的,这是对的)
func searchBarCancelButtonClicked(_ searchBar: UISearchBar){
self.navigationItem.searchController = nil
self.view.setNeedsLayout()
/* Cannot access tableview constraints from here because extension is outside of the class */
}https://stackoverflow.com/questions/52318218
复制相似问题