【发布时间】:2021-01-29 18:40:16
【问题描述】:
我正在快速开发一个应用程序,您可以在其中过滤 UICollectionView 中显示的数据。过滤数据后,集合视图应该更新,因此只有符合过滤器的项目才会可见(例如,价格超过 30 美元)。我无法更新集合视图,我已经尝试了几乎所有内容......(reloadData(),deleteItems(at:IndexPath),批处理等......)这是集合视图函数的代码:
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dogsSort.count
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.bounds.width, height: 150)
}
internal func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectedDog = dogsSort[indexPath.row]
print("selected dog " + selectedDog.name)
let vc = self.storyboard!.instantiateViewController(withIdentifier: "ItemVC") as! ItemViewController
vc.dog = selectedDog
self.navigationController!.pushViewController(vc, animated: true)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
cell.imageView.layer.cornerRadius = 10
/*storageWizard.getImage(path: "/dogs/" + dogsSort[indexPath.row].id + "/image.png", imageCompletionHandler: { (image) -> Void in
cell.imageView.image = image
self.dogsSort[indexPath.row].image = image
return
})*/
print(indexPath.row)
if dogsSort.count > indexPath.row {
cell.btnPrice.setTitle("Get for " + String.init(self.dogsSort[indexPath.row].price) + "$", for: .normal)
cell.labelView.text = self.dogsSort[indexPath.row].name
cell.CityView.text = self.dogsSort[indexPath.row].description
cell.breedView.text = self.dogsSort[indexPath.row].breed
cell.ageView.text = self.dogsSort[indexPath.row].age
cell.weightView.text = self.dogsSort[indexPath.row].weight
}
return cell
}
我目前正在使用的代码,只是用于测试功能的虚拟代码,但它不起作用......
dogsSort.remove(at: 0)
collectionView.deleteItems(at: [IndexPath(row: 0, section: 0)])
collectionView.reloadData()
【问题讨论】:
-
定义“不工作”。另外,根据您的代码,您不需要
dogsSort.count > indexPath.row。你的“虚拟代码”到底在哪里? -
是dogSort过滤后的数组还是原来的?
-
dogSort 是原始数组。然后我做类似 dogsSort = dogsSort.filter { dog in return dog.price > 50 }
-
@Larme 不工作 - 不刷新集合视图。不删除过滤的数据。我在按钮“过滤器”点击上调用虚拟代码。
标签: swift uicollectionview uicollectionviewcell