如何在UICollectionView上添加一个search栏?

我想允许我的应用程序的用户使用UICollectionView上方的UISearchBar来search图像。 根据我的理解,一个UICollectionView必须在UICollectionViewController才能正常工作。 但是,Xcode不会让我把一个search栏放在UICollectionViewController 。 我也不能使用通用的UIViewController作为集合视图将无法正常工作。 我怎样才能实现我想要的function?

使用Swift3 + Storyboard实现的CollectionView + SearchBar

创build标题视图:

创建标题视图

创buildsearch栏:

创建搜索栏

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

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

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

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

创buildsearch栏sockets

在自定义类中创建搜索栏插座

诀窍:将search栏代理连接到COLLECTION VIEW类,search栏出口转到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() } 

设置search栏代理

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

最后,您的search栏委托方法将在您的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() } } 

UICollectionView里面UICollectionViewControllerUICollectionViewControllerUICollectionView就像UITableView ,可以添加到任何地方。 所有你需要做的是实现UICollectionViewDelegateUICollectionViewDataSource协议。 您可以按照以下教程补充标题和添加search栏作为UICollectionView的补充标题。