Search code examples
iosswiftuicollectionviewuicollectionviewcell

Trying to determine cell width in a subclassed UICollectionViewCell


I have a somewhat basic subclassed UICollectionView Cell. I want to add a UIImageView to it, so every cell displays an image.

The image is displaying properly if I add explicit values to x:y:width:height, but I can't use self.contentView.frame.width to determine the size of the Collection View cell (for placing the image on the x axis)

class SubclassedCell: UICollectionViewCell {
    var myImageView: UIImageView!
    required init?(coder aDecoder: NSCoder) {
        super.init(coder:aDecoder)
        myImageView = UIImageView(frame: CGRect(x: (self.frame.width - 10.0), y: 50.0, width: 20.0, height: 20.0))
        myImageView.image = UIImage(named: "JustinBieber")
        self.contentView.addSubview(myImageView)
    }
}

In the above, (self.contentView.frame.width - 10.0) is not getting the size of the collection view cell, so the image does not display at all. If I explicitly put in a value for x, say 0, it shows.

How can I determine the size (width) of the subclassed collection view cell?


Solution

  • The initializer is called to early in the view lifecycle to accurately provide values for dimensions.

    A more idiomatic approach would be to layout your image in the layoutSubviews life cycle method. A trivial example is illustrated below

    class SubclassedCell: UICollectionViewCell {
    
        var myImageView: UIImageView!
        var imageDisplayed = false
    
        override func layoutSubviews() {
            super.layoutSubviews()
            if !imageDisplayed {
                myImageView = UIImageView(frame: CGRect(x: (self.frame.width - 10.0), y: 50.0, width: 20.0, height: 20.0))
                myImageView.image = UIImage(named: "JustinBieber")
                self.contentView.addSubview(myImageView)
                imageDisplayed = true
            }
        }
    }
    

    If you are using auto layout in your application, you may also want to consider adding the image and providing constraints instead of explicitly setting the image's frame.

    As illustrated in this answer - depending on your use case - their may be better ways to set up your cell.