【问题标题】:How to get indexPath in cell class?如何在单元类中获取 indexPath?
【发布时间】:2017-12-16 15:31:21
【问题描述】:

我正在尝试获取单元格类中 tableView 单元格的 indexPath。 我在表格视图单元格中有一个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”。然后,当我滚动时,每个单元格都会显示不同的数字。

【问题讨论】:

  • 为什么要显示 indexPath.row 值?如果你需要显示计数,你不能利用你用来填充数据的模型吗?
  • 每个 tableView 单元格都是应用程序中的一个子类别。 tableView indexPath.row 告诉 collectionView 它是哪个子类别,然后它可以从 Firebase 加载集合视图单元格等的数据。@RakshithNandish
  • 太好了,在你的collectionView单元格中有一个值,当你设置tableview时,使用你的模型数组计数,设置collectionview单元格的值。然后在填充集合视图时基于该值运行您的逻辑。
  • 没有理由一个单元需要知道它自己的当前索引路径。如果你相信它,那你就做错了。
  • 我在顶部有带有类别的选项卡,每个类别都有一个 tableView,每个单元格中都有一个 collectionView。每个 tableView 单元格都是一个子类别。 tableView indexPath.row 告诉 collectionView 要显示哪个子类别,而 collectionView indexPath.row 告诉 collectionView 单元格从 Firebase 加载哪些餐厅数据。什么是更正确的方法? (还是编码新手)@rmaddy

标签: ios swift uitableview uicollectionview


【解决方案1】:

一个简单的解决方案是,在你的 viewController 集合里面的 cellForItemAt 方法给单元格一个类似的标签

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
 }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-07
    • 1970-01-01
    • 2017-01-27
    相关资源
    最近更新 更多