First loading with itemlist is working fine but after filter the collection view is not updating. I have added a search bar and trying to filter the result but UICollectionview failed to update view.
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
}
//filtering the items into filterSearch but collection view is not updating according to filter.
func updateSearchResults(for searchController: UISearchController) {
filterSearch = itemList.filter { itemList in
return temList.name.lowercased().contains(searchText.lowercased())
}
self.collectionView?.reloadData()
}