The UIControllerView

UICollectionView was added last year with iOS 6. I decided to spend some time over the weekend and see what I can come up with. It was not easy, well it was until I build my project and there spacing of the cell items was different on various screen sizes.Wrong Cell spacing

What in the world is going on here?? I check the storyboard and the constraints are correctly configured. So I decide to go through the documentation and baaaayaaam!!

func collectionView(collectionView: UICollectionView, layout collectionViewLayout:

UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{

}

jesus_ok___telegram_sticker_by_jinkazama84-d8qqmqi

 We are not yet out of the woods. We just need to add a few lines of code and we are good to go.

1. Define the cell spacing
let cellSpacing = CGFloat(1)

2. Set left/right margin
let leftRightMargin = CGFloat(0)

3. Define the number of columns
let numColumns = CGFloat(3)

4. Get the width of the screen.
let screenWidth = UIScreen.mainScreen().bounds.width

5. Calculate the width
let totalCellSpace = cellSpacing * (numColumns - 1)
let width = (screenWidth - leftRightMargin - totalCellSpace) / numColumns

6. Set the height of the cell
let height = CGFloat(120)

Complete Code


 

Final Result

Correct cell Spacing

Misson complete. Things look better now. The cells size is now dynamic on all screens. Victory.

telegram-i-migliori-stickers-da-aggiungere-alla-vostra-collezione-3

Happy coding. My #Swift adventure continues.

1 Comment

  1. martha saka March 4, 2016 at 8:47 am

    Good stuff

Leave a comment

Your email address will not be published. Required fields are marked *