0
我以編程方式實現了我的搜索欄。對於表視圖中的默認行爲,我設法使其在標題視圖中工作。現在,我正在嘗試在一個collectionView中實現相同的實現,我似乎無法使其工作。現在我已經掙扎了好幾天,任何幫助它的比賽都會受到讚賞。 我張貼整個視圖控制器的情況下,我失去了一些東西:集合視圖實現問題中的編程搜索欄
import UIKit
import Firebase
import FirebaseDatabase
class NHSTrustSearchData: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, UISearchBarDelegate {
var setupNHSTSD = SetupNHSTSD()
var nhsTrusts = [NhsTrust]()
var nhsTrustsFiltered = [NhsTrust]()
let searchController = UISearchController(searchResultsController: nil)
override func viewDidLoad() {
super.viewDidLoad()
// Initialize the window
let window = UIWindow.init(frame: UIScreen.main.bounds)
window.makeKeyAndVisible()
setupNHSTSD.nhsTrustSearchData = self
setupNHSTSD.setupViews()
setupNHSTSD.collectioViewSetup()
setupBasicNavigationForSocialHealthcare()
setupNHSTSD.collectionView.dataSource = self as UICollectionViewDataSource
setupNHSTSD.collectionView.delegate = self
setupNHSTSD.collectionView.register(NHSTrustCell.self, forCellWithReuseIdentifier: "NHSTustCell")
setupNHSTSD.searchBar.delegate = self
navigationItem.title = "Choose NHS Trust"
print("User role remains: \(currentUserRole)")
fetchQuestions()
searchController.searchResultsUpdater = self as UISearchResultsUpdating
searchController.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
setupNHSTSD.searchBar = searchController.searchBar
}
func filterContentForSearchText(searchText: String, scope: String = "All") {
nhsTrustsFiltered = nhsTrusts.filter { trust in
return trust.nhsTrustName.localizedLowercase.contains(searchText.localizedLowercase)
}
setupNHSTSD.collectionView.reloadData()
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if searchController.isActive && searchController.searchBar.text != "" {
return nhsTrustsFiltered.count
}
return nhsTrusts.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "NHSTustCell", for: indexPath) as! NHSTrustCell
cell.backgroundColor = .white
cell.layer.borderColor = UIColor(white: 0.5, alpha: 0.3).cgColor
cell.layer.borderWidth = 0.3
let trust : NhsTrust
if searchController.isActive && searchController.searchBar.text != "" {
trust = nhsTrustsFiltered[indexPath.row]
} else {
trust = nhsTrusts[indexPath.row]
}
cell.nhsTrustName.text = trust.nhsTrustName
return cell
}
}
extension NHSTrustSearchData: UISearchResultsUpdating {
@available(iOS 8.0, *)
func updateSearchResults(for searchController: UISearchController) {
filterContentForSearchText(searchText: searchController.searchBar.text!)
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
filterContentForSearchText(searchText: searchController.searchBar.text!)
}
}