gpt4 book ai didi

swift - 垂直和水平滚动collectionView选择单元格问题

转载 作者:行者123 更新时间:2023-11-30 10:49:38 24 4
gpt4 key购买 nike

我有一个双向滚动的collectionView,我希望单元格backgroundView在选择时出现并在取消选择时消失。我声明了一个包含选定索引路径的数组,以在 cellForItemAt indexPath 函数中对其进行测试,但它不起作用。请提供任何帮助!这是我的代码:

    var selectedIndexPaths:[IndexPath]=[]

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
if(selectedIndexPaths.contains(indexPath)){
selectedIndexPaths=selectedIndexPaths.filter { $0 != indexPath }
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectedIndexPaths.append(indexPath)
collectionView.reloadItems(at: [indexPath])
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// swiftlint:disable force_cast
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: contentCellIdentifier,
for: indexPath) as! UserCollectionCell

if(selectedIndexPaths.contains(indexPath) ){
cell.backgroundView?.isHidden=false
}
else{
cell.backgroundView?.isHidden=true
}

return cell
}

最佳答案

删除

 func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
if(selectedIndexPaths.contains(indexPath)){
selectedIndexPaths=selectedIndexPaths.filter { $0 != indexPath }
}
}

当您选择一个单元格并自动取消选择之前选择的单元格时调用它,然后将其更改为

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

if selectedIndexPaths.contains(indexPath) {
selectedIndexPaths = selectedIndexPaths.filter { $0 != indexPath }
}
else {
selectedIndexPaths.append(indexPath)
}
collectionView.reloadItems(at: [indexPath])
}

关于swift - 垂直和水平滚动collectionView选择单元格问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54914235/

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