如何在UICollectionView上方添加搜索栏? [英] How can I add a search bar above a UICollectionView?

查看:493
本文介绍了如何在UICollectionView上方添加搜索栏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to allow users of my app to search for images using a UISearchBar above a UICollectionView. According to my understanding, a UICollectionView must be in a UICollectionViewController to work properly. However, Xcode won't let me put a search bar in a UICollectionViewController. I also can't use a generic UIViewController as the collection view won't work properly. How can I achieve the functionality that I want?

推荐答案

CollectionView + SearchBar Swift3 +故事板实施。

创建标题视图:

创建搜索栏:

创建可重复使用的视图自定义类

设置可重复使用的视图自定义类

创建搜索栏插座

技巧:将搜索栏代理连接到COLLECTION VIEW类,搜索栏插座去到CUSTOM可重复使用的视图类

实现协议的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上方添加搜索栏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆