首页 > 解决方案 > 如何获取 UICollectionViewCell 的 indexPath 并保存它

问题描述

我有一个UICollectionView,其中有 48 个方格。我希望代码知道UICollectionViewCell用户选择了哪个。用户选择后UICollectionViewCell,用户必须按下颜色,这VC也是。

如何获得被选中的单元格?

我这样做了:

func selectedCell (at indexPath: IndexPath) {
    let indexPathForFirstRow = indexPath
    gamePad.selectItem(at: indexPathForFirstRow, animated: false, scrollPosition: UICollectionView.ScrollPosition(rawValue: 0))
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell: UICollectionViewCell = gamePad.cellForItem(at: indexPath)!

    switch cell.backgroundColor {
    case UIColor.lightGray:
        cell.backgroundColor = UIColor.gray
    case UIColor.gray:
        cell.backgroundColor = UIColor.lightGray
    default:
        break
    }
}

标签: iosswiftuicollectionviewuicollectionviewcell

解决方案


试试这个代码

func selectedCell(forCell cell: UITableViewCell) -> IndexPath? {
        let cellPosition: CGPoint = cell.convert(CGPoint.zero, to: self)
        return self.indexPathForRow(at: cellPosition)
    }

推荐阅读