ios - 如何在单元格类中获取 indexPath?

标签 ios swift uitableview uicollectionview

我正在尝试获取单元格类中 tableView 单元格的 indexPath。 我在 TableView 单元格内有一个 collectionView,我正在尝试在 collectionView 单元格内制作标签以显示特定 collectionView 所在的 tableView 单元格的 indexPath.row。

目前我有

var indexPathForCell: indexPath 

在我的单元格中。

然后在 tableView 类中,我在 cellForRowAt indexpath 中有这个

cell.indexpathForCell = indexPath  
lbl.text = String(indexPathForCell.row)  

如果有“3”个或更少的 tableView 单元格,则此方法有效,但如果有更多,则第 4 行将显示“0”作为 indexPathForcell.row,当我在 collectionView 中滚动时,数字会从“0”更改为“3”甚至显示“1”。然后,当我滚动时,每个单元格都会显示不同的数字。

最佳答案

一个简单的解决方案是,在集合 cellForItemAt 方法内的 viewController 中,为单元格提供一个标签,如

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SignupSelectCourseCollectionViewCell", for: indexPath) as! SignupSelectCourseCollectionViewCell

    cell.tag = indexPath.row

    return cell
}

现在您可以访问单元格类中的标记属性,例如

    override var isSelected: Bool {
didSet {

    let indexPathRow = self.tag
 }
}

关于ios - 如何在单元格类中获取 indexPath?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47847192/

相关文章:

ios - 在 TestFlight 上使用过期的构建

ios - iOS LinkedIn SDK 没有回调

ios - RxSwift 回调在结果之前先返回

iOS+ swift : Why is music not played on iPad?

ios - 二维码添加多个键值对

ios - LayoutSubviews 问题

objective-c - UIActivityIndi​​cator 和 GCD/线程

iphone - 在 iOS 7 中将 UIAlertView 中的消息对齐到左侧

objective-c - UIScrollView 中的 UIScrollView,如何在两者之间滚动时保持平滑过渡

ios - 如何从用户函数中获取对单元格的引用