CollectionView + SearchBar with Swift3 + Storyboard的實現。
創建頁眉查看:
創建搜索欄:
創建可重用的視圖定製類
將可重複使用的視圖定製類
創建搜索欄出口
絕招:將搜索家庭AR代表對集合視圖類,搜索欄出口前進到CUSTOM REUSABLE視圖類
實現協議
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 {
最後,你的搜索欄委託方法會在你的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()
}
}
主要的想法是,你沒有設置爲的CollectionView搜索欄;您爲resultArray中的數據設置searchBar,然後使用searchResult中的數據實例化newCollectionView,並將其添加到initialCollectionView –