How to make the search bar work in uicollectionview

I want to place the search bar above the uicollection view, as shown below. I want to do this programmatically. enter image description here

current view

my implementation

This is my code for the search bar customization feature. I have this in a home view controller.

func setupSearchBar() {

    let searchBar = UISearchBar(frame: CGRect(x: 0, y: 64, width:UIScreen.main.bounds.width, height: 32))
    searchBar.barTintColor = UIColor(red: 64/255, green: 64/255, blue: 64/255, alpha: 1)
    searchBar.backgroundColor = UIColor.blue
    searchBar.isTranslucent = true
    searchBar.placeholder = "Search Timeline"
    searchBar.searchBarStyle = UISearchBarStyle.prominent
    view.addSubview(searchBar)

} 
+4
source share
2 answers

Try adding this code:

    // Call sizeToFit() on the search bar so it fits nicely in the UIView
    self.searchController!.searchBar.sizeToFit()
    // For some reason, the search bar will extend outside the view to the left after calling sizeToFit. This next line corrects this.
    self.searchController!.searchBar.frame.size.width = self.collectionView!.frame.size.width
+1
source

You can add a search bar to your UICollectionview header.

This creates a programmatic searchBar search.

    lazy var searchBar : UISearchBar = {
    let s = UISearchBar()
        s.placeholder = "Search Timeline"
        s.delegate = self
        s.tintColor = .white
        s.barTintColor = // color you like
        s.barStyle = .default
        s.sizeToFit()
    return s
}()

Next, the header register is loaded in your view.

collectionView?.register(UICollectionViewCell.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerCellId")

Override the method below to determine the height at which you want your title to be.

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    return CGSize(width: view.frame.width, height: 40)
}

, UICollectionview, .

    override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headerCellId", for: indexPath)
        header.addSubview(searchBar)
        searchBar.translatesAutoresizingMaskIntoConstraints = false
        searchBar.leftAnchor.constraint(equalTo: header.leftAnchor).isActive = true
        searchBar.rightAnchor.constraint(equalTo: header.rightAnchor).isActive = true
        searchBar.topAnchor.constraint(equalTo: header.topAnchor).isActive = true
        searchBar.bottomAnchor.constraint(equalTo: header.bottomAnchor).isActive = true
    return header
}
+1

Source: https://habr.com/ru/post/1680047/


All Articles