![](/img/trans.png)
[英]How do I add a view at the top of a UICollectionView for supporting things like a search bar or filter in objective-c?
[英]How can I add a search bar above a UICollectionView?
我想允許我的應用程序的用戶使用UICollectionView
上方的UISearchBar
搜索圖像。 根據我的理解, UICollectionView
必須在UICollectionViewController
才能正常工作。 但是,Xcode不會讓我在UICollectionViewController
放置搜索欄。 我也不能使用通用的UIViewController
因為集合視圖將無法正常工作。 如何實現我想要的功能?
CollectionView + SearchBar與Swift3 + Storyboard實現。
創建標題視圖:
創建搜索欄:
創建可重用的視圖自定義類
設置可重用的視圖自定義類
創建搜索欄插座
技巧:將搜索欄代表連接到COLLECTION VIEW類,搜索欄出口轉到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()
}
設置搜索欄代理
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
沒有UICollectionViewController
。 UICollectionView
就像UITableView
,可以在任何地方添加。 您需要做的就是實現UICollectionViewDelegate
和UICollectionViewDataSource
協議。 您可以按照以下教程Supplementary Header並添加搜索欄作為UICollectionView
的補充標題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.