Setting Corner Radius on UIImageView not working

I'm at a bit of a loss. I've used the layer property of UIView to round the corners of multiple elements in my app. However, this one UIImageView is simply not complying. Not sure what I am missing.

The UIImageView (called previewImage) is contained in a Table View Cell. I've tried setting the cornerRadius property multiple location (in the cell itself and in the controller that creates the cell) to no avail.

static NSString *CellIdentifier = @"MyTableViewCell";

MyTableViewCell *cell = (MyTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil];
    cell = [topLevelObjects objectAtIndex:0];
    cell.previewImage.layer.cornerRadius = 20; //Made it 20 to make sure it's obvious.
}

Is there something about the way cells are loaded that I'm missing?


You need to set the layer's masksToBounds property to YES:

cell.previewImage.layer.masksToBounds = YES;

This is because the UIImageView control creates a pseudo-subview to hold the UIImage object.


Also worth noting that

  1. If you are using aspectFit AND cornerRadius with clipsToBounds/masksToBounds, you won't get the rounded corners.

i.e if you have this

theImageView.contentMode = .scaleAspectFit

and

   theImageView.layer.cornerRadius = (theImageView.frame.size.height)/2
    theImageView.clipsToBounds = true

or

theImageView.layer.masksToBounds = true

It won't work. you will have to get rid of aspectFit code

//theImageView.contentMode = .scaleAspectFit
  1. Make sure the width and the height for the Image View is same

This should work

cell.previewImage.clipsToBounds = YES;

cell.previewImage.layer.cornerRadius = 20;

I believe you need to set:

cell.previewImage.layer.masksToBounds = YES;
cell.previewImage.layer.opaque = NO;

In Xcode Interface Builder, selecting 'Clip Subviews' Drawing attribute for the view together with setting the corner radius in the code cell.previewImage.layer.cornerRadius = 20;does the job for me!

See 'Clip Subviews' option in IB