我有一个双向滚动collectionView,我希望单元格backgroundView在选中时显示,而在取消选中时消失。 我声明了一个带有选定indexPaths的数组,以便在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
}
答案 0 :(得分:0)
删除
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])
}