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

A T*_*hka 12 uiviewcontroller uisearchbar ios uicollectionview

我想允许我的应用程序的用户使用UISearchBar上面的a 搜索图像UICollectionView.根据我的理解,UICollectionView必须在一个UICollectionViewController正常工作.但是,Xcode不会让我把搜索栏放在一个UICollectionViewController.我也不能使用泛型,UIViewController因为集合视图将无法正常工作.如何实现我想要的功能?

mou*_*igo 38

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

    }
Run Code Online (Sandbox Code Playgroud)

设置搜索栏代理

    class MyCollectionViewController: (other delegates...), UISearchBarDelegate {
Run Code Online (Sandbox Code Playgroud)

最后,您的搜索栏委托方法将在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()
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,这种方法有一些副作用; 搜索栏将出现在每个部分标题中,搜索栏将滚出视图,当调用self.collectionView?.reloadData()时,搜索栏将失去其firstResponder状态.查看Jeremiah-de一步一步的回购,以便将UISearchController与UICollectionView一起使用https://github.com/jeremiah-de/CollectionViewSearch/tree/basic-collection-view (7认同)
  • SO 内的完整教程。- 未来是现在 - (3认同)
  • 很好的解释和图片,谢谢你的努力,+1 (2认同)