Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a search bar above a UICollectionView?

I would like to allow users of my app to search for images using a UISearchBar above a UICollectionView. According to my understanding, a UICollectionView must be in a UICollectionViewController to work properly. However, Xcode won't let me put a search bar in a UICollectionViewController. I also can't use a generic UIViewController as the collection view won't work properly. How can I achieve the functionality that I want?

like image 346
A Tyshka Avatar asked Jul 13 '16 15:07

A Tyshka


2 Answers

CollectionView + SearchBar with Swift3 + Storyboard implementation.

Creating the Header View:

Creating the Header View

Creating the Search Bar:

Creating the Search Bar

Create the reusable view custom class

Create the reusable view custom class

Set the reusable view custom class

Set the reusable view custom class

Create the search bar outlet

Create the search bar outlet in custom class

Trick: Connect the search bar delegate to COLLECTION VIEW class, the search bar outlet goes to the CUSTOM REUSABLE VIEW CLASS

Connect the search bar delegate to collection view class

Implement the CollectionView header method of protocol

    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 the Searchbar delegate

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

And finally, your the search bar delegate 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()
    }
}
like image 178
mourodrigo Avatar answered Nov 17 '22 17:11

mourodrigo


It is not mandatory to have UICollectionView inside UICollectionViewController. UICollectionView is just like UITableView and can be added anywhere. All you need to do is implement UICollectionViewDelegate and UICollectionViewDataSource protocols. You can follow following tutorial Supplementary Header and add search bar as a supplementary header of UICollectionView.

like image 2
Vishnu gondlekar Avatar answered Nov 17 '22 18:11

Vishnu gondlekar