[英]Hide search bar when cancel button is pressed, and resize navbar
我在導航欄中使用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 */
}
}
添加一行代碼如下:
func searchBarCancelButtonClicked(_ searchBar: UISearchBar){
self.navigationItem.searchController = nil
self.view.setNeedsLayout()
/* 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 */
}
嘗試像這樣更新導航控制器內的視圖:
func searchBarCancelButtonClicked(_ searchBar: UISearchBar){
navigationItem.searchController = nil // or searchController
navigationController?.view.setNeedsLayout() // invalidate current layout
navigationController?.view.layoutIfNeeded() // force update layout
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.