UICollectionView - 找出当前索引路径并更改 values/data

UICollectionView - Find out current index path and change values/data

我想知道如何捕获我的集合视图的当前索引路径。

我用的是横流,下面我已经说明了:

  func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 3
    }

有三个预定义的单元格,我希望相应地更改三个集合视图单元格中每个单元格的 text/UI 元素。我怎样才能做到这一点?我真的很挣扎,因为目前我得到了 3 个充满相同数据的单元格。这是预期的。

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

               let cell = detailsCollectionView.dequeueReusableCell(withReuseIdentifier: "DetailsCollectionViewCell", for: indexPath) as! DetailsCollectionViewCell
                cell.layer.shadowRadius = 1
                cell.layer.shadowOpacity = 0.1
                cell.layer.shadowOffset = CGSize(width: 2.5, height: 5)

                return cell
        }
    }
}

但本质上我希望执行以下伪代码:

    if cell.indexPath == 0 {
      label.text = "This is the first cell"

    } else if cell.indexPath == 1 {
     label.text = "This is the second cell"

    } else if cell.indexPath == 2 {
     label.text = "This is the third cell"
   }
}

如果这是一个愚蠢的问题,我们深表歉意。

感谢您的宝贵时间。

您应该比较 cellForItemAtindexPath 参数的 item 属性。

if indexPath.item == 0 {
    //first item
}