我正在尝试获取单元格类中 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/