Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 297
Fdo Avatar asked Jul 10 '15 01:07

Fdo


3 Answers

It is very simple just do this:

imageView.contentMode = UIViewContentMode.ScaleAspectFill;
imageView.layer.masksToBounds = YES;
like image 184
Hic Up Avatar answered Oct 25 '22 22:10

Hic Up


[yourImageView setContentMode:UIViewContentModeScaleAspectFill]; yourImageView.layer.masksToBounds = YES;

like image 38
Reza.Ab Avatar answered Oct 25 '22 23:10

Reza.Ab


I think you should be using:

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

instead of this:

  cell.contentMode = UIViewContentMode.ScaleAspectFill
  cell.clipsToBounds = true
like image 31
Lavvo Avatar answered Oct 25 '22 23:10

Lavvo