【问题标题】:How can I add a search bar above a UICollectionView?如何在 UICollectionView 上方添加搜索栏?
【发布时间】:2016-11-16 06:37:18
【问题描述】:

我想允许我的应用用户使用UISearchBar 上方的UICollectionView 搜索图像。据我了解,UICollectionView 必须在UICollectionViewController 中才能正常工作。但是,Xcode 不允许我在UICollectionViewController 中添加搜索栏。我也不能使用通用的UIViewController,因为集合视图无法正常工作。如何实现我想要的功能?

【问题讨论】:

标签: ios uiviewcontroller uicollectionview uisearchbar


【解决方案1】:

CollectionView + SearchBarSwift3 + Storyboard 实现。

创建标题视图:

创建搜索栏:

创建可重用视图自定义类

设置可复用视图自定义类

创建搜索栏出口

技巧:将搜索栏代理连接到 COLLECTION VIEW 类,搜索栏出口转到 CUSTOM REUSABLE VIEW CLASS

实现协议的CollectionView头方法

    override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

         if (kind == UICollectionElementKindSectionHeader) {
             let headerView:UICollectionReusableView =  collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "CollectionViewHeader", for: indexPath)

             return headerView
         }

         return UICollectionReusableView()

    }

设置搜索栏委托

    class MyCollectionViewController: (other delegates...), UISearchBarDelegate {

最后,您的搜索栏委托方法将在您的 CollectionView 类中调用

//MARK: - SEARCH

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    if(!(searchBar.text?.isEmpty)!){
        //reload your data source if necessary
        self.collectionView?.reloadData()
    }
}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    if(searchText.isEmpty){
        //reload your data source if necessary
        self.collectionView?.reloadData()
    }
}

【讨论】:

  • 不幸的是,这种方法有一些副作用;搜索栏将出现在每个部分的标题中,搜索栏将滚动到视图之外,并且当 self.collectionView?.reloadData() 被调用时,搜索栏将失去其 firstResponder 状态。查看 Jeremiah-de 的逐步存储库,以使用 UISearchController 和 UICollectionView github.com/jeremiah-de/CollectionViewSearch/tree/…
  • @mourodrigo 嘿,当我尝试覆盖该 collectionView 方法 (viewForSupplementaryElementOfKind) 时,xCode 抛出错误“方法不会覆盖其超类中的任何方法”。我确实将搜索栏委托添加到我的 viewController 和那个插座,我也将 UISearchBarDelegate 设置到了我的 viewController ......运行代码时的一个问题是搜索栏没有呈现,有标题空间但里面没有 searchBar
  • @Manu , viewForSupplementaryElementOfKind 不需要方法签名实现的“覆盖”。我想这可能会解决您的问题。如果您需要其他任何东西,请在我的收件箱上联系我。 =)
  • 很好的解释和图片,谢谢你的努力,+1
  • SO 中的完整教程。 – 未来就是现在 –
【解决方案2】:

UICollectionView 不是必须包含在 UICollectionViewController 中。 UICollectionView 就像UITableView 一样,可以添加到任何地方。您需要做的就是实现UICollectionViewDelegateUICollectionViewDataSource 协议。您可以按照以下教程Supplementary Header 并添加搜索栏作为UICollectionView 的补充标题。

【讨论】:

  • 我做到了,但即使我实现了 UICollectionViewDelegate 和 UICollectionViewDataSource,我也得到了 NSExceptions
  • 异常是什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多