Search code examples
iosswiftuiimageviewcontrollercollectionview

Set rounded corners on UIimage in UICollectionViewCell in swift


I have a simple problem that I cannot find a solution to on google, the docs or here.

I have a Collectionview in my view controller. I have created a custom cell, DescriptionCell, that contains a UIImage. I want this image to have rounded corners. However, I don't know where to set the cornerradius on the UIImage layer. I have tried in the cells' awakeFromNib method, in the delegate method CellForRowAtIndexPath and overriden LayoutSubview in the cell but it does not work. Where should I put the code to set the radius for the UIImage?

To specify, I know how to create rounded corners of a UIImage. But if it is a subview of a Collectionview cell, I do not know where to set the cornerradius.

Here is code for my descriptionCell

class DescriptionCell: UICollectionViewCell {
    @IBOutlet weak var mImage: UIImageView!

    override func awakeFromNib() {
    //mImage.layer.cornerradius = 5 
    //Does not work, the image is still square in the cell
    }

And in the cellforRowAtIndePath

 func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell = collectionView.dequeueReusableCellWithReuseIdentifier("descriptioncell", forIndexPath: indexPath) as! DescriptionCell
    //cell.mImage.layer.cornerradius = 5 
    //Does not work, the image is still square in the cell
return cell    
}

Thanks in advance!


Solution

  • Well you're using part of the code from the answer you said you were using. the other part is imageView.clipsToBounds = true

    Update your awakeFromNib like this:

    override func awakeFromNib() {
        mImage.layer.cornerRadius = 5 
        mimage.clipsToBounds = true
    }
    

    To make it a circle you need to set cornerRadius to half of the square height. In your cellForItemAtIndexPath add these lines:

    cell.layoutIfNeeded()
    cell.mImage.layer.cornerRadius = cell.mImage.frame.height/2
    

    Update

    To avoid layoutSubviews from being called twice, override layoutSubviews in your DescriptionCell class and put the code there:

    override func layoutSubviews() {
        super.layoutSubviews()
        layoutIfNeeded()
        mImage.layer.cornerRadius = mImage.frame.height/2
    }