我应该如何解决这个问题?我不知道如何正确地将Search Bar与UICollectionView集成。请帮我理解这个问题。
P.S。我的语言是Swift
[1]
[2]
import UIKitclass MainViewController: UICollectionViewController {
override func viewDidLoad() { super.viewDidLoad() } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 14 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TrendingGifCell", for: indexPath) return cell }
}
答案 0 :(得分:3)
尝试以下代码,它应该可以解决您的问题:
class MainViewController: UICollectionViewController,UISearchControllerDelegate, UISearchBarDelegate, UISearchResultsUpdating {
var searchController : UISearchController!
override func viewDidLoad() {
super.viewDidLoad()
//Search at the top
self.searchController = UISearchController(searchResultsController: nil)
self.searchController.searchResultsUpdater = self
self.searchController.delegate = self
self.searchController.searchBar.delegate = self
self.searchController.hidesNavigationBarDuringPresentation = false
self.searchController.dimsBackgroundDuringPresentation = true
self.searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.becomeFirstResponder()
self.navigationItem.titleView = searchController.searchBar
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 14
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TrendingGifCell", for: indexPath)
return cell
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
self.dismiss(animated: true, completion: nil)
}
func updateSearchResults(for searchController: UISearchController)
{
print("updating")
}
}
让我知道它的工作原理:)。
答案 1 :(得分:2)