Search code examples
swiftxcodeuicollectionviewuicollectionviewcelluisearchcontroller

UiSearchController to UiCollectionView in Swift


I want to add Search bar programmatically. I want it to look like in Settings App (appear when scrolling down and disappear when scrolling up).

But Search Bar doesn't appear.

Outline: enter image description here

ViewController:

import UIKit

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UISearchControllerDelegate, UISearchBarDelegate, UISearchResultsUpdating {

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

    @IBOutlet weak var collectionView: UICollectionView!

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

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView.delegate = self
        collectionView.dataSource = self

        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..."
        searchController.searchBar.sizeToFit()
        searchController.searchBar.becomeFirstResponder()
        self.navigationItem.titleView = searchController.searchBar

        self.definesPresentationContext = true
        self.searchController.searchBar.placeholder = "Search for Items"

    }

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

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

            if searchActive {
                return filtered.count
            }
            else
            {
                return items.count
            }
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell

        cell.contentView.layer.cornerRadius = 7.0
        cell.contentView.layer.borderWidth = 1.0
        cell.contentView.layer.borderColor = UIColor.clear.cgColor
        cell.contentView.layer.masksToBounds = false
        cell.layer.cornerRadius = 7.0

        return cell
    }

    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()
    }
}

App is working, showing items, but there is no search bar while scrolling. Maybe this is because I am using UiCollectionView instead of UiTableView and I have to add some additional code? What am I missing?

Video, how it looks: https://drive.google.com/file/d/1P0carjjgiForBnK_UmiuBWWk5A7BqSWB/view?usp=sharing


Solution

  • Your code is not working because you don’t have a navigation controller. At least it doesn’t show in the code or in the video. If you don’t, you need to embed the viewController in a navigationController.