按下取消按钮时隐藏搜索栏,并调整导航栏的大小

问题描述 投票:3回答:2

我在导航栏中使用UISearchController实现了一个搜索栏。还有一个表格视图,其顶部约束设置在导航栏的底部。

期望的行为:当按下取消按钮时,搜索栏被隐藏,表格视图的顶部约束返回到删除搜索栏之前的状态(参见本文末尾的屏幕截图#1)

当前行为:当按下取消按钮时,搜索栏消失,但tableView的顶部约束不会响应(参见屏幕截图#3)

解决此问题的可能方法是在单击取消按钮时手动更新约束。但是,我找不到从UISearchBarDelegate方法访问tableView的约束的方法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 */
    }
}

在按下搜索按钮之前。

在按下取消按钮之前。 enter image description here

按下取消按钮后。 enter image description here

ios swift uitableview constraints uisearchcontroller
2个回答
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
投票

(是的,这是对的)

func searchBarCancelButtonClicked(_ searchBar: UISearchBar){

   self.navigationItem.searchController = nil

   self.view.setNeedsLayout()

 /* Cannot access tableview constraints from here because extension is outside of the class */
}
© www.soinside.com 2019 - 2024. All rights reserved.