ios - 按下取消按钮时隐藏搜索栏,并调整导航栏的大小
问题描述
我有一个使用UISearchController
导航栏内部实现的搜索栏。还有一个表视图,其顶部约束设置为导航栏的底部。
期望的行为:当取消按钮被按下时,搜索栏被隐藏并且表格视图的顶部约束返回到搜索栏被删除之前的状态(参见本文末尾的屏幕截图#1 )
当前行为:按下取消按钮时,搜索栏消失但 tableView 的顶部约束没有响应更改(参见屏幕截图 #3)
此问题的一个可能解决方案是在单击取消按钮时手动更新约束。但是,我找不到从该方法访问 tableView 约束的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 */
}
}
解决方案
添加一行代码如下:
func searchBarCancelButtonClicked(_ searchBar: UISearchBar){
self.navigationItem.searchController = nil
self.view.setNeedsLayout()
/* Cannot access tableview constraints from here because extension is outside of the class */
}
推荐阅读
- python - 使用 Python 连接字符串参数
- c - K&R c 书籍第 5.2 节 getint 示例
- xcode - 在 iOS 上我应该检查什么,并且我的本地化字符串没有被本地化?
- java - 0/1背包算法的解释
- typescript - 打字稿中变量之前的$$是什么?
- java - 从标准 Java 应用程序运行 Spring Boot jar
- mongodb - 是否可以在 mongo 中的每次单击时对 db 执行读取操作
- amazon-web-services - Apache Web 服务器在使用负载均衡器 dns 名称时工作,但不是 Route53 指向负载均衡器
- javascript - AmCharts v4 - 日期和线条问题
- javascript - 如何返回元素 React