kaminsky59 kaminsky59 - 1 month ago 7
Swift Question

Add Subview within a custom subclassed UICollectionViewCell class

This might be a simple question but I can't get it work nor can I find an answer to the question.

I am trying to add a subview to a custom subclassed collectionviewcell when calling a method from the viewcontroller.

I have a

didSelectItemAtIndexPath
created in the viewcontroller. When I click one of the cells, I call the
addOverlay
method in the custom cell class to add a subview but this does not seem to show up. Any help would be useful. Thank you

Sample code:

func addOverlayView() {
let overlayView = UIView(frame: CGRectMake(0, 0, 50, 50))
overlayView.backgroundColor = UIColor.blueColor()
contentView.addSubview(overlayView)
}

Answer

Did you get a proper cell reference like this at the didSelectItemAtIndexPath method?

if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? YourCustomCollectionViewCell {
   cell.addOverlayView()
}