UIImage Scale Aspect Fill and Clip Subviews not working in UICollectionView

I have a UICollectionView with a cell containing one UIImageView. I set the frame.size of the UIImageView to match the frame.size of the cell, and also explicitly request the scale of the UIImageView using Aspect Fill and Clip Subview as follows in the 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 image (PICTURE A) , but when I click (tap) the image that it magically resolves, Asview Fill and Clip Subviews (IMAGE B) . I can’t understand why this happens only after the tap, and not when loading images for the first time. They are output asynchronously to the server, but scaling occurs only after the image tap (the switching function is also not implemented).

NOTE. The UICollectionView is configured in the storyboard view manager, and in the Collection view and in the reusable cell, the Fill Aspect and Clip subheadings are activated.

IMAGE A (incorrect scaling - stretched and without cropping):

IMG A

IMAGE B (correct scaling after the tap):

IMG B

+6
source share
2 answers

It is very simple, just do it.

 imageView.contentMode = UIViewContentMode.ScaleAspectFill; imageView.layer.maskToBounds=YES; 
+6
source

I think you should use:

 imageView.contentMode = UIViewContentMode.ScaleAspectFill imageView.clipsToBounds = true 

instead of this:

  cell.contentMode = UIViewContentMode.ScaleAspectFill cell.clipsToBounds = true 
+5
source

All Articles