第一次加载 itemlist 工作正常,但过滤后集合视图没有更新。我添加了一个搜索栏并尝试过滤结果,但 UICollectionview 无法更新视图。
var resultSearchController = UISearchController()
//itemlist
var itemList = [item1, item2, item3, item4,..]
//configured searchbar
func viewDidLoad() {
self.resultSearchController = UISearchController(searchResultsController: nil)
self.resultSearchController.searchResultsUpdater = self
self.resultSearchController.searchBar.delegate = self
self.definesPresentationContext = true
self.resultSearchController.dimsBackgroundDuringPresentation = false
self.resultSearchController.searchBar.placeholder = "Search for Items"
self.resultSearchController.searchBar.searchBarStyle = UISearchBarStyle.prominent
self.resultSearchController.searchBar.sizeToFit()
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if resultSearchController.isActive {
return filterSearch.count
}
return itemList.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var item = itemList()
if resultSearchController.isActive {
item = filterSearch[indexPath.row]
} else {
item = itemList[indexPath.row]
}
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellIdentifier", for: indexPath)
cell.titleLabel.text = item
return cell
}
//将项目过滤到filterSearch但集合视图没有根据过滤器更新。
func updateSearchResults(for searchController: UISearchController) {
filterSearch = itemList.filter { itemList in
return temList.name.lowercased().contains(searchText.lowercased())
}
self.collectionView?.reloadData()
}