UISearchController搜索栏与CollectionView

时间:2017-06-13 12:40:00

标签: ios swift uicollectionview overlap uisearchcontroller

以编程方式启动UISearchController时,UISearchBar与下面的CollectionView重叠。

我在这里和那里搜索过,似乎以前没有人遇到过这种问题。

enter image description here enter image description here

我如何能够做到这一点有一些限制:

  • 无法使用tableview标题
  • 无法使用collectionview标题
  • 必须使用collectionviewcontroller

已经尝试过调整滚动视图插入和扩展边缘 - 没用,因为它的CollectionViewController

问题是:如何以正确的方式使用IBAction? 连接到放大镜的IBAction代码是:

@IBAction func showSearchBar(_ sender: UIBarButtonItem) {
    let searchController = UISearchController(searchResultsController: nil)
    searchController.searchResultsUpdater = self
    searchController.dimsBackgroundDuringPresentation = false
    present(searchController, animated: true, completion: nil)
}

1 个答案:

答案 0 :(得分:0)

感谢@noir_eagle建议我已经为present(searchController, animated: true, completion: nil)方法实现了完成块,所以它看起来像这样:

present(searchController, animated: true, completion: {
        UIView.animate(withDuration: 0.25, animations: {
            self.collectionView?.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)
            self.collectionView?.contentOffset = CGPoint(x: 0, y: -64)
        })
    })

我必须在此方法中执行此操作,因为UISearchControllerDelegate方法didPresentSearchController(_ searchController: UISearchController)willPresentSearchController(_ searchController: UISearchController)永远不会被调用...不知道为什么。

接下来,以某种方式,didDismissSearchController(_ searchController: UISearchController)的方法UISearchControllerDelegate在使用取消按钮解除UISearchBar之后立即调用,因此我实现了这一点:< / p>

func didDismissSearchController(_ searchController: UISearchController) {
    UIView.animate(withDuration: 0.25, animations: {
        self.collectionView?.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)
    })
}

这很好......流畅的动画,直到我意识到属性searchController.hidesNavigationBarDuringPresentation true ,所以我所要做的就是将其设置为

那就是它,不需要contentInsetcontentOffset动画! 最终解决方案如下所示:

@IBAction func showSearchBar(_ sender: UIBarButtonItem) {
    let searchController = UISearchController(searchResultsController: nil)
    searchController.searchResultsUpdater = self
    searchController.dimsBackgroundDuringPresentation = false
    searchController.hidesNavigationBarDuringPresentation = false
    present(searchController, animated: true, completion: nil)
}