Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I have image views in a collection view resize themselves depending on the screen size?

I have a collection view of image views, and when run in the simulator on an iPhone 7, the layout is how I want it - images displayed 3 per line, with no spacing in between. However when I run it on my phone (iPhone 6+), there is spacing between the images.

These are the functions that set up the layout:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsetsMake(0,0,0,0)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let imgWidth = view.bounds.width/3.0
    let imgHeight = imgWidth

    return CGSize(width: imgWidth, height: imgHeight)
}

I was thinking that sizeForItem would re-scale the images by stating that the width would be the screen width divided by three, and the height equal to that. But I think I'm confused about that and perhaps it's only resizing the cell, and not the image view within. However I'm not sure where I can set the image view size to scale dynamically with the screen size.

How can I change it so the image cells in the collection view resize themselves accordingly, and remain 3 per line with no spacing, regardless of screen size?

EDIT: After putting cell.postImage.contentMode = UIViewContentMode.scaleAspectFill into cellForItem method:

enter image description here

EDIT 2: After trying iOSFreak's solution, problem still persists:

enter image description here

like image 683
KingTim Avatar asked Nov 22 '25 09:11

KingTim


1 Answers

You change Estimate Size "None".

enter image description here

like image 97
ikbal Avatar answered Nov 23 '25 21:11

ikbal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!