简体   繁体   中英

How to get indexPath in cell class?

I'm trying to get the indexPath of a tableView cell in the cell class. I've got a collectionView inside the table view cells and I'm trying to make label inside the collectionView cell show the indexPath.row of the tableView cell that particular collectionView in.

Currently i have

var indexPathForCell: indexPath 

in my cell class.

Then in the tableView class i have this in cellForRowAt indexpath

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

If there is "3" or fewer tableView cells this works but if theres more then the 4th row then shows "0" as the indexPathForcell.row, and as I scroll in the collectionView the numbers then chnage from "0" to "3" and even show "1". Each cell then shows a different number as i scroll.

a simple solution for that is, in your viewController inside the collection cellForItemAt method gives the cell a tag like

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

    cell.tag = indexPath.row

    return cell
}

and now you can access tag property in cell class like

    override var isSelected: Bool {
didSet {

    let indexPathRow = self.tag
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM