SunShine SunShine -4 years ago 165
Swift Question

get all the subviews of a cell onClick in UICollectionView swift

I am trying to access all the subviews attached to the cell in

UICollectionView
when the cell is clicked.

I am able to add the image and label to it, but it shows nil when I tap on any cell

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath)

// Image
let imageview:UIImageView = UIImageView(frame: CGRect(x: 5, y: 5, width: myCell.frame.width - 10, height: myCell.frame.height - 20))
imageview.image = UIImage(named: String(format: "%@.png", arr[indexPath.row]))
imageview.tag = 20

// Label
let label = UILabel(frame: CGRect(x: 5, y: 50, width: myCell.frame.width - 10, height: myCell.frame.height - 40))
label.textAlignment = .center
label.text = arr[indexPath.row]
label.textColor = .black
label.tag = 21
label.font = label.font.withSize(8)

myCell.contentView.addSubview(imageview)
myCell.contentView.addSubview(label)

myCell.backgroundColor = UIColor.white

return myCell
}


and I am trying to access the subviews as below:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath)
print(myCell.contentView.subViews) // Returns null
}


I am aware that we can get the item index using
indexPath.row
. But I want read the subview. How to get it ? Thanks for your help

Answer Source
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath)
    print(myCell.contentView.subViews) // Returns always null 
}

The method of UITableView dequeueReusableCell returns a new reusable cell and now myCell have the new reference and always be new reference if you want to get your old cell you need to getting the cell from

let cell = collectionView.cellForItemAtIndexPath(indexPath) as! MyCell

if you have the class use MyCell else you can get cell directly without type casting.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItemAtIndexPath(indexPath)
    print(cell.contentView.subviews)
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download