Search code examples
iosiphoneuiimageviewuicollectionview

UIImage Scale Aspect Fill and Clip Subviews not working in UICollectionView


I have a UICollectionView with a cell containing a single UIImageView. I'm setting the UIImageView frame.size to match the cell's frame.size and also explicitly asking the UIImageView to Scale with Aspect Fill & Clip Subview the following way in cellForItemAtIndexPath method:

let cell:UICollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! UICollectionViewCell

... 

var imageView = UIImageView(image: self.eventImages[indexPath.row])
imageView.frame.size = cell.frame.size
cell.contentMode = UIViewContentMode.ScaleAspectFill
cell.clipsToBounds = true
imageView.contentMode = UIViewContentMode.ScaleAspectFill
imageView.clipsToBounds = true
cell.addSubview(imageView)

The result is a stretched out image (IMAGE A), but when I click (tap) the image it "magically" resolves the Aspect Fill & Clip Subviews (IMAGE B) . I can't seem to understand why this is happening only after a tap and not when loading the images for the first time. They are fetched asynchronously to a server, but the scaling only occurs after a tap of the image (there is also no tap functionality implemented).

NOTE: The UICollectionView is set up in a storyboard View Controller, both the Collection View and the Reusable Cell have Aspect Fill and Clip Subviews enabled.

IMAGE A (wrong scaling - stretched out and no cropping):

IMG A

IMAGE B (correct scaling after tap):

IMG B


Solution

  • It is very simple just do this:

    imageView.contentMode = UIViewContentMode.ScaleAspectFill;
    imageView.layer.masksToBounds = YES;