如何在UICollectionView上添加一个search栏?
我想允许我的应用程序的用户使用UICollectionView
上方的UISearchBar
来search图像。 根据我的理解,一个UICollectionView
必须在UICollectionViewController
才能正常工作。 但是,Xcode不会让我把一个search栏放在UICollectionViewController
。 我也不能使用通用的UIViewController
作为集合视图将无法正常工作。 我怎样才能实现我想要的function?
使用Swift3 + Storyboard实现的CollectionView + SearchBar 。
创build标题视图:
创buildsearch栏:
创build可重用的视图自定义类
设置可重用的视图自定义类
创buildsearch栏sockets
诀窍:将search栏代理连接到COLLECTION VIEW类,search栏出口转到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() }
设置search栏代理
class MyCollectionViewController: (other delegates...), UISearchBarDelegate {
最后,您的search栏委托方法将在您的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
有UICollectionViewController
。 UICollectionView
就像UITableView
,可以添加到任何地方。 所有你需要做的是实现UICollectionViewDelegate
和UICollectionViewDataSource
协议。 您可以按照以下教程补充标题和添加search栏作为UICollectionView
的补充标题。