突出显示两个CollectionView中的单元格

时间:2018-09-28 10:20:05

标签: swift uicollectionview uicollectionviewcell

我在CollectionView中使用两个ViewController。每个CollectionView有5个单元格。我还使用isSelected检测每个CollectionView的选定单元格(并突出显示选定的单元格)。在每个CollectionView中,只能选择(突出显示)一个单元格。

一切正常,但是有一个问题。

在模拟器中,当我选择索引从0到3的单元格时,一切正常。但是问题出在我选择索引为4的单元格时。这在两个CollectionView中都突出显示索引为4的单元格。

仅当在另一个屏幕上不可见带有另一个CollectionView的索引4的单元格时,才会发生这种情况(我对两个集合视图都使用了水平滚动,一次只能在屏幕上看到5个单元格中的三个)

我的代码下面:

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()
    }

1 个答案:

答案 0 :(得分:1)

selectIndex = (indexPath as NSIndexPath).row collectionView.reloadData()

这部分没有确切说明要选择哪个集合视图。它只是索引,两个集合视图都将被选中。您没有看到0-3的唯一原因是您没有重新加载其他集合视图。但是第四个索引必须重新加载(滚动查看时会被选中)。

每个集合视图必须使用2个不同的索引

例如:

selectIndex1selectIndex2

相关问题