close
Add Search on UICollectionView using Swift

In this tutorial we will add search on UICollectionView in swift. This is the simplest and the most easiest way to add search bar in UICollectionView, so let’s dive into tutorial right away.

Setting up the interface:

Add a view controller to your storyboard and insert a uicollectionview into it.

Insert a label in the cell of the collection view

Give cell an identifier

Make class for cell toolCollectionViewCell

Assign toolsCollectionViewCell to UICollectionView cell.

and Also connect the Label in the cell to it’s respective class

Setting up UICollectionView:

Here is a step by step process for you to set up UICollectionView:

  1. Add CollectionView Delegate and DataSource
  2. Make an array with items you want to display:
  3. Make IBOutlet of CollectionView
  4. In viewDidLoad() add
  5. Add UICollectionView DataSource Methods

  6. The method I’m adding below is not mandatory. So I’m just adding this in case you want to use it. Tis method handles what will happen when someone tap on an item in uicollectionview:

That is it for your UICollectionView. If you run now you’ll see it’s showing the values in the collection view. Next we will add UISearchBar into our system

Implementing Search for UICollectionView

We will implement it the same as setting up UICollectionView. A step by step process to implement search in UICollectionView, but first let’s embed our view controller into a Navigation Controller.

  1. Add delegates
  2. Declare the following variables
  3. In viewDidLoad() add these lines
  4. Add all of these methods that will make you search bar work!
  5. Lastly you need to update numberOfItemsInSection of uicollectionview. Replay the method fully with:

Run the project and the search bar will be up and running.

Tags : add searchbar on collection viewcollection view searchcollectionview swift tutorialswift uisearchbar implementationtutorial collection view swiftuisearch on collectionview
Chaudhary Talha

The author Chaudhary Talha

I'm an iOS developer by profession and UI/UX designer by passion. All my tutorials are based on my personal experiences and whenever I learn something new I share it with the world.

Leave a Response

x
Like what we are doing? Join Us! Become a contributor at iOS Pakistan.