使用 Swift3 + Storyboard 实现 CollectionView + SearchBar。
创建 Header View:
![创建 Header View](https://istack.dev59.com/uzCft.webp)
创建搜索栏:
![创建搜索栏](https://istack.dev59.com/0TjMt.webp)
创建可重用的视图自定义类
![创建可重用的视图自定义类](https://istack.dev59.com/kjfX3.webp)
设置可重用的视图自定义类
![设置可重用的视图自定义类](https://istack.dev59.com/bQhna.webp)
创建搜索栏 outlet
![在自定义类中创建搜索栏 outlet](https://istack.dev59.com/ErjxH.webp)
技巧:将搜索栏委托连接到 COLLECTION VIEW 类,搜索栏 outlet 连接到 CUSTOM REUSABLE VIEW CLASS。
![将搜索栏委托连接到 collection view 类](https://istack.dev59.com/6CQPT.webp)
实现协议的 CollectionView header 方法
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类中被调用。
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
if(!(searchBar.text?.isEmpty)!){
self.collectionView?.reloadData()
}
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if(searchText.isEmpty){
self.collectionView?.reloadData()
}
}