user10916200
user10916200

Reputation:

Linking a search bar to a collection view

I have a collection view with cells, I've added the search bar into the navigation bar but I'm having trouble being able to set it so that when I enter text in the search bar it filters the cells to only leave the ones that match the text in the search bar can anyone help me

I know the normal way of using the search bar is with a table view but I'm trying to do it with collection views

Upvotes: 0

Views: 131

Answers (1)

lloydTheCoder
lloydTheCoder

Reputation: 144

Hope below piece of code helps,

class SearchCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    let searchController = UISearchController(searchResultsController: nil)

    override func viewDidLoad() {
        super.viewDidLoad()

        searchController.searchResultsUpdater = self
        searchController.obscuresBackgroundDuringPresentation = false
        searchController.searchBar.placeholder = "Enter text"
        searchController.isActive = true
        navigationItem.searchController = searchController
        definesPresentationContext = true

    }
}

extension SearchCollectionViewController: UISearchResultsUpdating {
    func updateSearchResults(for searchController: UISearchController) {
        let searchText =  searchController.searchBar.text
        //Here you can update/filter cells in collection view
    }
}

Upvotes: 1

Related Questions