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

时间:2016-07-13 15:15:55

标签: ios uiviewcontroller uicollectionview uisearchbar

我想允许我的应用的用户使用UISearchBar上方的UICollectionView搜索图片。根据我的理解,UICollectionView必须在UICollectionViewController才能正常运作。但是,Xcode不允许我在UICollectionViewController中放置一个搜索栏。我也无法使用通用UIViewController,因为集合视图无法正常工作。如何实现我想要的功能?

2 个答案:

答案 0 :(得分:32)

使用 Swift3 + Storyboard 实施

CollectionView + SearchBar

创建标题视图

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 in custom class

技巧:将搜索栏代表连接到COLLECTION VIEW类,搜索栏出口转到CUSTOM REUSABLE VIEW CLASS

Connect the search bar delegate to collection view class

实现协议的CollectionView标头方法

while (token1.IsCancellationRequested)
{
}

设置搜索栏代理

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

    }

最后,您的搜索栏委托方法将在您的CollectionView类中调用

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

答案 1 :(得分:1)

UICollectionViewUICollectionViewController不是强制性的。 UICollectionView就像UITableView一样,可以添加到任何地方。您需要做的就是实现UICollectionViewDelegateUICollectionViewDataSource协议。您可以按照以下教程Supplementary Header添加搜索栏作为UICollectionView的补充标题。

相关问题