Search code examples
iosswiftuicollectionviewinstagram-api

Display Instagram photos correctly in a CollectionView on all screen sizes


This one has me perplexed. Ok, here we go. I'm pulling down IG images, they come in 3 sizes: 150x150, 306x306, 640x640

What I would like to do is display them 3 across, on all iPhone screen sizes (5,5S,6,6+). The 306x306 sizes come down super fast, and look great. So that's my starting point (150x150 are a bit blurry, 640x640 is also an option, I can also use those, just trying to save some bandwidth).

The edges can be flush to the sides, with a 1 px/pt line between them. I have kind of wracked my brain around this. My understanding is that the function (below) should override any other setting in my Storyboard, and where I should be focused (I've printed out the sizes I've captured from println().

My challenge is finding out the final widths and heights needed to work on all screens. I've tried a number of permutations, but have not nailed it yet. I'm close, but no cigar. This is all using a CollectionView in storyboards. Advice appreciated. It's a heck of a problem, spent all day on this one.

I don't think autolayout can help at all, it all has to be done in code, but who knows?

Thanks [lots!] :-)

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

    var width = CGRectGetWidth(collectionView.bounds)

    println("width: \(width)")

    // iphone5 320
    // iphone5S 320
    // iphone6 375
    // iphone 6+ 414

    return CGSize(width: NeedCorrectWidthHere, height: NeedCorrectHeightHere)

}

This does partially work, with a gap between images:

var screenWidth = CGRectGetWidth(collectionView.bounds)
var cellWidth = screenWidth/3

return CGSize(width: cellWidth-10, height: cellWidth-10)

Solution

  • This seemed to work. A pretty simple solution in the end.

       func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    
        var screenWidth = CGRectGetWidth(collectionView.bounds)
        var cellWidth = screenWidth/3
    
        return CGSize(width: cellWidth-2, height: cellWidth-2)
    
    }
    
        func collectionView(collectionView: UICollectionView,
            layout collectionViewLayout: UICollectionViewLayout,
            minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
                return 3
        }
    
        func collectionView(collectionView: UICollectionView,
            layout collectionViewLayout: UICollectionViewLayout,
            minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
                return 3
        }