2

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

2 Answers 2

1

Are you running in iOS 11? Did you pull down the collection view? the search bar only appears when pull down. The only difference that I see with one that I have working is this, the navigationItem searchcontroller:

self.navigationItem.searchcontroller = searchcontroller
Sign up to request clarification or add additional context in comments.

4 Comments

iOS 12. I've added that code line, but nothings change. I'm pulling down, but there is no search bar.
Why do you exactly need this? searchBarCancelButton? if you scroll up the collectionView it should be automatically hidden without add any code Also the dimsBackgroundDuringPresentation has the same behaviour as obscures method so I would delete that
I have tried your code, and it works for me, the searchBar is just fixed in the navigationBar but it works... Did you set up your UInavigationController?
How should I set up the UInavigationController?
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.