ios - 根据单击的单元格更改变量

标签 ios swift uicollectionviewcell collectionview

我想在点击某个 CollectionView 单元格时将变量设置为不同的字符串。因此,cell1 被点击,然后 var cellTapped = "cell1",cell 2 被点击,然后 var cellTapped = "cell2" 等等。有人建议我

"create a custom cell and hold the value as property and read this value on didSelectCell()"

但我不确定该怎么做(新手)。

( swift 3)

最佳答案

您需要将 UICollectionViewDelegate 设置为您的 ViewController,然后实现 didSelectItemAt IndexPath,当点击单元格时调用它。

像这样:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    cellTapped = "cell" + String(indexPath.row)
}

您还可以拥有一个字符串数组,并根据 indexPath.row 对该数组进行索引:

let cellStringValues = ["cell1", "cell2", "cell3", ... , "celln"]

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    cellTapped = cellStringValues[indexPath.row]
}

关于ios - 根据单击的单元格更改变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43644823/

相关文章:

ios - 如何在 SpriteKit 中创建暂停标签?

ios - 什么是适用于 iOS 的良好数据可视化库?

ios - Swift:如何将 UIScrollView contentSize 高度设置为内容的高度?

ios - 我应该将私有(private) IBOutlet 设为内部以便进行单元测试吗?

ios - 水平设置 UICollectionView header 时应用程序崩溃

ios - UIcollectionView奇怪的细胞回收行为

c++ - iOS 不合格 id 错误

ios - Swift 中的多个 Storyboard

ios - 我的自定义 UITableViewCell 中的所有标签都被压扁了

ios - 如何从 UICollectionViewCell 呈现一个 AlertView