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.
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{
}
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
Misson complete. Things look better now. The cells size is now dynamic on all screens. Victory.
Happy coding. My
#Swift
adventure continues.