How can I add a search bar above a UICollectionView?

前端 未结 2 1439
栀梦
栀梦 2021-02-14 00:43

I would like to allow users of my app to search for images using a UISearchBar above a UICollectionView. According to my understanding, a UIColle

2条回答
  •  迷失自我
    2021-02-14 01:11

    CollectionView + SearchBar with Swift3 + Storyboard implementation.

    Creating the Header View:

    Creating the Search Bar:

    Create the reusable view custom class

    Set the reusable view custom class

    Create the search bar outlet

    Trick: Connect the search bar delegate to COLLECTION VIEW class, the search bar outlet goes to the CUSTOM REUSABLE VIEW CLASS

    Implement the CollectionView header method of protocol

        override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    
             if (kind == UICollectionElementKindSectionHeader) {
                 let headerView:UICollectionReusableView =  collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "CollectionViewHeader", for: indexPath)
    
                 return headerView
             }
    
             return UICollectionReusableView()
    
        }
    

    Set the Searchbar delegate

        class MyCollectionViewController: (other delegates...), UISearchBarDelegate {
    

    And finally, your the search bar delegate methods will be called in your CollectionView Class

    //MARK: - SEARCH
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        if(!(searchBar.text?.isEmpty)!){
            //reload your data source if necessary
            self.collectionView?.reloadData()
        }
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        if(searchText.isEmpty){
            //reload your data source if necessary
            self.collectionView?.reloadData()
        }
    }
    

提交回复
热议问题