gpt4 book ai didi

swift - UICollection View 中的搜索栏不是搜索结果

转载 作者:行者123 更新时间:2023-11-30 12:01:27 24 4
gpt4 key购买 nike

我正在尝试制作可以过滤 UICollectionView 搜索结果的搜索栏。我制作了一个自定义 UICollectionViewCell

class toolCollectionViewCell: UICollectionViewCell {

@IBOutlet weak var imageViewCell: UIImageView!
@IBOutlet weak var toolTitle: UILabel!

}

这两个IBoutlets都链接 Storyboard中的相应元素。用于将搜索结果过滤到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()
}

The problem is that search is not working correctly. Search result always filter to First item of collection view. How to correct the search? you can download the project.

最佳答案

您忘记在此方法中更改单元格文本:

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
}

这不适用于图像。您必须使用以食物名称作为键、图像作为值的字典,或者更好地创建类似带有标题字段和图像字段的类 Food 的内容。然后按标题过滤此类。

我也改变了这个方法:

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

关于swift - UICollection View 中的搜索栏不是搜索结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47162607/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com