如何获取 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
}
}

试试这段代码

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

最新更新