I have a UICollectionView and each UICollectionViewCell is a custom class with a UIImageView
@interface MyCollectionViewCell : UICollectionViewCell
@property (weak, nonatomic) IBOutlet UIImageView *image;
@end
Then I have an image I would like to fit inside the imageview. But I can't get the image to fit properly inside the image view. Here's the image. those are the exact dimensions, I think that's a 36x36 but essentially I don't want the size to matter I just want it to scale down and fit regardless of the size. The dimensions of the UIImageView in the storyboard is 59x54 ( I know this can change depending on how the screen wants to display the cells so again size should not be relevant) These are the current display settings for the view in storyboard And my UICollectionView delegate code
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 3;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return 3;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
MyCollectionViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
[cell.image setImage:[UIImage imageNamed:@"avocado"]];
return cell;
}
The result looks like this So you see how the edge is slightly cut off. I did read a few other answers of trying [cell.image setContentMode:UIViewContentModeScaleAspectFit];
but that didn't work either. Does anyone have a solution for this? The UIImageView is fit inside the UICollectionViewCell like so
The outer blue line is the UICollectionViewCell and the inner blue line is the UIImageView.
Make sure you add top, leading, bottom, and trailing constraints between the image view and the cell so that the image view is sized correctly when the cell changes size - otherwise the image view will remain this size seen in the storyboard even if the cell changes size.
You will also for sure need to change your image view's Content Mode
(seen in your storyboard image) from Scale to Fill
to Aspect Fit
in order for the image to scale without stretching.