我在一个ViewController
中使用两个CollectionView
。每个CollectionView
有 5 个单元格。我还使用isSelected
来检测每个CollectionView
的选定单元格(并突出显示选定的单元格(。在每个CollectionView
中,只能选择一个单元格(突出显示(。
一切都按预期工作,但有一个问题。
在模拟器中,当我选择一个索引从 0 到 3 的单元格时,一切正常。但是当我选择索引为 4 的单元格时,问题就变成了。这将突出显示两个CollectionView
中索引为 4 的单元格。
仅当另一个CollectionView
的索引为 4 的单元格在屏幕上不可见时,才会发生这种情况(我对两个集合视图都使用水平滚动,并且屏幕上一次只有 5 个单元格中的 3
个可见(。在我的代码部分下面:
var selectIndex = 1
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == self.percentsCollectionView {
let cell:PercentCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: percentsCellIdentifiers[indexPath.item], for: indexPath) as! PercentCollectionViewCell
if selectIndex == (indexPath as NSIndexPath).row
{
cell.isSelected = true
}
else
{
cell.isSelected = false
}
return cell
}
else {
let cell:PersonCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: personsCellIdentifiers[indexPath.item], for: indexPath) as! PersonCollectionViewCell
if selectIndex == (indexPath as NSIndexPath).row
{
cell.isSelected = true
}
else
{
cell.isSelected = false
}
return cell
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectIndex = (indexPath as NSIndexPath).row
collectionView.reloadData()
}
selectIndex = (indexPath as NSIndexPath).row
collectionView.reloadData()
这部分并不完全说明要选择哪个集合视图。 它只是索引,两个集合视图都将被选中。对于 0-3,您看不到此内容的唯一原因是您没有重新加载其他集合视图。但是第 4 个索引必须重新加载(当您滚动查看它时(它将被选中。
您必须为每个集合视图使用 2 个不同的索引
例如:
selectIndex1
和selectIndex2