ios - 如何获取 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)
}
推荐阅读
- sql - MSSQL 选择父母 ID 值
- android - 如何在android中的图层列表(我没有png)中显示文本而不是位图中的图像
- hibernate - JPA Hibernate 使用标准左外连接,而实体中没有实际映射
- css - 设置固定标头后剩余空间 100%
- c# - WPF Datagrid 或者其他可以在第一列缩进的东西?
- javascript - 使用 async/await 和 firebase firestore 下载图像
- swiftui - SwiftUi - 通过函数更改视图
- flutter - Flutter - 自定义字体系列不适用于应用
- android - 防止关闭屏幕出现Android
- bash - Nethogs 测量的带宽与文件大小不匹配