CollectionView + SearchBar with Swift3 + Storyboard implementation.
Create header:

Creating a search bar:

Create a reusable custom class

Define a custom reusable class class

Create an output to the search bar

Trick: Connect the search panel delegate to the COLLECTION VIEW class, the output to the search bar will appear in the CUSTOM REUSABLE VIEW CLASS

Introduce Protocol CollectionView Header Method
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() }
Set a search bar delegate
class MyCollectionViewController: (other delegates...), UISearchBarDelegate {
And finally, your search bar delegation methods will be called in your CollectionView class
//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() } }
source share