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

标签 ios swift uitableview constraints uisearchcontroller

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

期望的行为:按下取消按钮时,搜索栏被隐藏,表格 View 的顶部约束恢复到搜索栏被删除之前的状态(参见屏幕截图#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 */
    }
}

在按下搜索按钮之前。

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

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

最佳答案

添加一行代码如下:

func searchBarCancelButtonClicked(_ searchBar: UISearchBar){

   self.navigationItem.searchController = nil

   self.view.setNeedsLayout()

 /* Cannot access tableview constraints from here because extension is outside of the class */
}

关于ios - 按下取消按钮时隐藏搜索栏,并调整导航栏的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52318218/

相关文章:

ios - SKScene : Move & resize debugging fields

iphone - iOS 我可以增加一个 NSNumber,还是需要创建一个新的?

ios - 更改状态栏颜色

ios - 代码永远不会执行错误

带有自定义 View Controller 的 iOS 共享扩展

python - 如何使 MLModel 在 Swift CoreML 中可更新?

ios - 为 UITableView 使用 RxCocoa 扩展时,如何控制 canEditRowAtIndexPath

ios - 如何在 Objective C 中创建 UITextField 的自定义委托(delegate)

iphone - UITableView 点击以取消选择单元格

iphone - TVOutManager 在模拟器上工作,但不在设备上工作?