Alexei Kukhto Alexei Kukhto - 1 month ago 23
iOS Question

Search bar does not appear in header of UICollectionView when I run my project

How I should do right with this issue? I don't know how I can integrate Search Bar with UICollectionView correctly. Please help me understand this problem.

P.S. My language is Swift

My view in Interface Builder [1]

My view when I run project [2]


import UIKit

class MainViewController: UICollectionViewController {

override func viewDidLoad() {
super.viewDidLoad()
}



override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 14
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TrendingGifCell", for: indexPath)
return cell
}


}


Answer

Try code below , it should solve your problem:

    class MainViewController: UICollectionViewController,UISearchControllerDelegate, UISearchBarDelegate, UISearchResultsUpdating {

    var searchController : UISearchController!

    override func viewDidLoad() {
        super.viewDidLoad()


        //Search at the top
        self.searchController = UISearchController(searchResultsController:  nil)

        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.becomeFirstResponder()

        self.navigationItem.titleView = searchController.searchBar



}



    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 14
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TrendingGifCell", for: indexPath)
        return cell
    }

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    self.dismiss(animated: true, completion: nil)
}

func updateSearchResults(for searchController: UISearchController)
{
    print("updating") 
}


    }

Let me know how it works :).

Comments