UIImage Scale Aspect Fill and Clip Subviews not working in UICollectionView
Asked Answered
O

4

15

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

Operate answered 10/7, 2015 at 1:23 Comment(0)
K
29

It is very simple just do this:

imageView.contentMode = UIViewContentMode.ScaleAspectFill;
imageView.layer.masksToBounds = YES;
Kibosh answered 31/8, 2016 at 9:40 Comment(4)
should be imageView.layer.masksToBounds = YES;Pyroelectricity
what else do you see, I wrote?Kibosh
Swift 4 = imageView.layer.maskToBounds = trueSheriesherif
In my case, it worked when I have set width and height constraints.Spermophyte
T
7

I think you should be using:

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

instead of this:

  cell.contentMode = UIViewContentMode.ScaleAspectFill
  cell.clipsToBounds = true
Tuttle answered 10/7, 2015 at 3:0 Comment(2)
Nope, had both but also just tried commenting the cell scaling and leaving only the imageView scaling but didn't work. In the storyboard both the Collection View and the Collection Reusable Cell have Aspect Fill and Clip Subviews... Any recomendations on something different that might work in there?Operate
In my case, it worked when I have set width and height constraints.Spermophyte
A
1

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

Arabia answered 24/4, 2018 at 12:23 Comment(0)
C
-1

imageView.contentMode = UIView.ContentMode.scaleAspectFill imageView.layer.masksToBounds = true

Corody answered 16/11, 2023 at 16:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.