Search code examples
iosswiftxcodeuicollectionviewuisearchcontroller

Add horizontally scrollable filter options under UISearchController


I am developing a page that allows the user to search contents in a table, and I want to add some filter options under the search bar. I've added the UISearchController programmatically into the navbar, but I want to know how to add a list of horizontally scrollable filter options under the search bar (Just like the layout on the right in this picture: https://i.sstatic.net/XrjIq.png). Thanks!

I realize that this is probably something that has been asked/answered before, but I cannot find a single page discussing this. If you have a link to a solution I would really appreciate it!


Solution

  • You can create a horizontally scrolling collectionView with filter buttons in them and set it below the UISearchController.

    You can create a collection view like this programmatically:

     lazy var collectionView: UICollectionView = {
            let layout = UICollectionViewFlowLayout()
            layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
            layout.minimumInteritemSpacing = 0
            layout.scrollDirection = UICollectionViewScrollDirection.horizontal
            let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
            cv.backgroundColor =  UIColor.white
            cv.dataSource = self
            cv.delegate = self
            cv.translatesAutoresizingMaskIntoConstraints = false
            return cv
        }()
    

    Now you can add items to this collectionView using cellForItemAtIndexPath, numberOfItemsInSection and other delegates.

    You would need to then set constraints on the collectionView like this:

     collectionView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
    collectionView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
    collectionView.topAnchor.constraint(equalTo: searchController.bottomAnchor).isActive = true
    collectionView.heightAnchor.constraint(equalToConstant: 44).isActive = true
    

    Let me know if you need further explanation.