簡體   English   中英

如何在UICollectionView上方添加搜索欄?

[英]How can I add a search bar above a UICollectionView?

我想允許我的應用程序的用戶使用UICollectionView上方的UISearchBar搜索圖像。 根據我的理解, UICollectionView必須在UICollectionViewController才能正常工作。 但是,Xcode不會讓我在UICollectionViewController放置搜索欄。 我也不能使用通用的UIViewController因為集合視圖將無法正常工作。 如何實現我想要的功能?

CollectionView + SearchBarSwift3 + Storyboard實現。

創建標題視圖:

創建標題視圖

創建搜索欄:

創建搜索欄

創建可重用的視圖自定義類

創建可重用的視圖自定義類

設置可重用的視圖自定義類

設置可重用的視圖自定義類

創建搜索欄插座

在自定義類中創建搜索欄插座

技巧:將搜索欄代表連接到COLLECTION VIEW類,搜索欄出口轉到CUSTOM REUSABLE VIEW CLASS

將搜索欄委托連接到集合視圖類

實現協議的CollectionView頭方法

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

    }

設置搜索欄代理

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

最后,您的搜索欄委托方法將在CollectionView類中調用

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

UICollectionView沒有UICollectionViewController UICollectionView就像UITableView ,可以在任何地方添加。 您需要做的就是實現UICollectionViewDelegateUICollectionViewDataSource協議。 您可以按照以下教程Supplementary Header並添加搜索欄作為UICollectionView的補充標題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM