如何在UICollectionView上方添加搜索栏?

15
我想让我的应用程序用户可以使用位于UICollectionView上方的UISearchBar搜索图像。据我了解,UICollectionView必须在UICollectionViewController中才能正常工作。但是,Xcode不允许我将搜索栏放在UICollectionViewController中。我也不能使用通用的UIViewController,因为集合视图将无法正常工作。我该如何实现所需的功能?

请查看以下链接,这可能会对您有所帮助。示例-如何将UICollectionview与UISearchbar集成-1 - Chandan
2个回答

46

使用 Swift3 + Storyboard 实现 CollectionView + SearchBar。

创建 Header View:

创建 Header View

创建搜索栏:

创建搜索栏

创建可重用的视图自定义类

创建可重用的视图自定义类

设置可重用的视图自定义类

设置可重用的视图自定义类

创建搜索栏 outlet

在自定义类中创建搜索栏 outlet

技巧:将搜索栏委托连接到 COLLECTION VIEW 类,搜索栏 outlet 连接到 CUSTOM REUSABLE VIEW CLASS。

将搜索栏委托连接到 collection view 类

实现协议的 CollectionView header 方法

    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()
    }
}

12
很遗憾,这种方法会产生一些副作用:搜索栏将出现在每个部分标题中,搜索栏将滚动消失,并且当调用self.collectionView?.reloadData()时,搜索栏将失去其firstResponder状态。请查看Jeremiah-de的逐步操作库,了解如何在UICollectionView中使用UISearchController https://github.com/jeremiah-de/CollectionViewSearch/tree/basic-collection-view - aumansoftware
@mourodrigo 嘿,当我尝试覆盖collectionView方法(viewForSupplementaryElementOfKind)时,xCode会抛出错误“该方法不覆盖其超类的任何方法”。我已将searchbar委托添加到我的viewController和outlet中,我也将UISearchBarDelegate设置为我的viewController...运行代码时的一个问题是搜索栏没有被渲染,有标题空间但没有搜索栏。 - Manu
1
@Manu,viewForSupplementaryElementOfKind方法的实现不需要在方法签名上加上“override”。我猜这可能会解决你的问题。如果你需要其他帮助,请私信联系我。=) - mourodrigo
2
非常好的解释,并配有图片,感谢您的努力,+1。 - mAc
3
在 Stack Overflow 内部进行的全面教程。- 未来已来 - - Mars

2

UICollectionView不一定非要在UICollectionViewController中使用,它就像UITableView一样可以添加到任何地方。您只需要实现UICollectionViewDelegateUICollectionViewDataSource协议。您可以参考以下教程Supplementary Header,将搜索栏作为UICollectionView的补充头部。


我已经这样做了,但是即使我实现了UICollectionViewDelegate和UICollectionViewDataSource,我仍然会收到NSExceptions。 - A Tyshka
1
什么是异常? - Vishnu gondlekar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接