我正在尝试制作可以过滤UICollectionView
搜索结果的搜索栏。我做了一个自定义UICollectionViewCell
类
class toolCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageViewCell: UIImageView!
@IBOutlet weak var toolTitle: UILabel!
}
这两个IBoutlets
都链接了故事板中的相应元素。将搜索结果过滤到UICollectionView
func updateSearchResults(for searchController: UISearchController)
{
let searchString = searchController.searchBar.text
filtered = items.filter({ (item) -> Bool in
let countryText: NSString = item as NSString
return (countryText.range(of: searchString!, options: NSString.CompareOptions.caseInsensitive).location) != NSNotFound
})
collectionView.reloadData()
}
问题是搜索无法正常工作。 搜索结果始终会过滤到收藏视图的第一项。如何更正搜索?你可以download项目。
答案 0 :(得分:0)
您忘记更改此方法中的单元格文字:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! toolCollectionViewCell
//configureCell(cell: cell as! toolCollectionViewCell, forItemAtIndexPath: indexPath as NSIndexPath)
cell.imageViewCell=cell.viewWithTag(1) as! UIImageView
if searchActive {
cell.imageViewCell.image=imageViewArray[indexPath.row]
cell.toolTitle.text = filtered[indexPath.row]
} else {
cell.imageViewCell.image=imageViewArray[indexPath.row]
cell.toolTitle.text = items[indexPath.row]
}
return cell //return your cell
}
这对图像无效。您必须使用带有食物名称的字典作为键,将图像作为值,或者更好地创建类似带有标题字段和图像字段的类食物。然后用它的标题过滤这个类。
我也改变了这个方法:
func updateSearchResults(for searchController: UISearchController) {
// better way is to use "guard" or "if let searchString = searchString { ... }",
// because using searchString! could produce a crash in some cases.
guard let searchString = searchController.searchBar.text else {
return
}
filtered = items.filter({ (item) -> Bool in
let countryText: NSString = item as NSString
return countryText.lowercased.contains(searchString.lowercased())
})
collectionView.reloadData()
}
以下是类和图像的工作示例 - Download