How to add a search bar over a UICollectionView?

I want users of my application to be able to search for images using the UISearchBar above the UICollectionView . In my opinion, the UICollectionView should be in the UICollectionViewController for it to work properly. However, Xcode will not let me put the search string in the UICollectionViewController . I also cannot use a generic UIViewController , as the collection view will not work properly. How can I achieve the desired functionality?

+11
source share
3 answers

CollectionView + SearchBar with Swift3 + Storyboard implementation.

Create header:

Create a title

Creating a search bar:

Create a search bar

Create a reusable custom class

Create a custom reusable class

Define a custom reusable class class

Set custom reusable view class

Create an output to the search bar

Create output in search string in custom class

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

Connect a search bar delegate to a collection 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() } } 
+32
source

It is not necessary to have a UICollectionView inside a UICollectionViewController . UICollectionView similar to UITableView and can be added anywhere. All you have to do is implement the UICollectionViewDelegate and UICollectionViewDataSource . You can follow the next tutorial, Optional Title, and add a search string as an optional UICollectionView title.

+1
source
-1
source

All Articles