Get updates on your email

Tuesday, June 27, 2017

Implementing UISearch in Collection View with swift

In this tutorial we will implement UiCollectionView and add a UISearchBar on it using swift 3.

Setting 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. (Ignore the search bar you see on the top)



and Also connect the Label in the cell to it's respective class (Ignore the search bar you see on the top)


Set up UICollectionView

In ViewController.swift (which is a class you have associated with your view controller in which you have collection view and search bar)

Add UICollectionViewDelegate, UICollectionViewDataSource

Make and array with items you want to display:

var items = ["Apple", "Orange"]

In viewDidLoad() add

collectionView.delegate = self
        collectionView.dataSource = self


Next we will implement Data Source methods

//MARK: UICollectionViewDataSource
    func collectionView(_ collectionView: UICollectionView,numberOfItemsInSection section: Int) -> Int {
        return items.count    //return number of rows in section
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath) as! toolCollectionViewCell
        
        //configureCell(cell: cell as! toolCollectionViewCell, forItemAtIndexPath: indexPath as NSIndexPath)
        
        cell.toolTitle.text = items[indexPath.row]
        
        return cell      //return your cell
    }

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 collection view:

//MARK: UICollectionViewDelegate
//    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//        // When user selects the cell
//    }


Now if you run it you'll see the collection view working. But the search bar will not display at the moment and we need to add it manually.

Implementing Search Bar

After implementing the collection view we will now update our code and integrate search into it.

Add UISearchControllerDelegate, UISearchBarDelegate, UISearchResultsUpdating

We need three more variables to implement search:

 var filtered:[String] = []
    var searchActive : Bool = false
let searchController = UISearchController(searchResultsController: nil)


in ViewDidLoad after you have assigned delegate and datasource of collectionView to self add these lines of code:

self.searchController.searchResultsUpdater = self
        self.searchController.delegate = self
        self.searchController.searchBar.delegate = self
        
        self.searchController.hidesNavigationBarDuringPresentation = false
        self.searchController.dimsBackgroundDuringPresentation = true
        self.searchController.obscuresBackgroundDuringPresentation = false
        searchController.searchBar.placeholder = "Search for tools and resources"
        searchController.searchBar.sizeToFit()
        
        searchController.searchBar.becomeFirstResponder()
        
        self.navigationItem.titleView = searchController.searchBar

If you look at last line of this code above: self.navigationItem.titleView indicated that I've added the search bar in the navigation bar. You can add a view and add it in there etc.

You need to update a data source method of CollectionView called numberOfItemsInSection

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if searchActive {
            return filtered.count
        }
        else
        {
        return items.count
        }
    }


Finally implement all the methods that will make your search bar work.

//MARK: Search Bar
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        searchActive = false
        self.dismiss(animated: true, completion: nil)
    }
    
    func updateSearchResults(for searchController: UISearchController)
    {
        let searchString = searchController.searchBar.text
        
        filtered = items.filter({ (item) -> Bool in
            let countryText: NSString = item as NSString
            
            return (countryText.range(of: searchString!, options: NSString.CompareOptions.caseInsensitive).location) != NSNotFound
        })
        
        collectionView.reloadData()

    }
    
    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        searchActive = true
        collectionView.reloadData()
    }
    
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchActive = false
        collectionView.reloadData()
    }
    
    func searchBarBookmarkButtonClicked(_ searchBar: UISearchBar) {
        if !searchActive {
            searchActive = true
            collectionView.reloadData()
        }
        
        searchController.searchBar.resignFirstResponder()
    }



Run the project and you'll see the search running perfectly.





















1 comment:

  1. hello ! how to add image & label in UICollectionView with SearchBar please

    ReplyDelete