Alex Smith Alex Smith - 6 months ago 20
Swift Question

Change width of every 3rd cell in collection view

I want to change the width of every 3rd cell in a collection view. Currently, I'm setting the width and height of elements like this:

func collectionView(collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let width = UIScreen.mainScreen().bounds.size.width
return CGSize(width: width / 2, height: width/2)
}


How can I select every 3rd element in the collection view and make that element full width? In css, it'd be element:nth-child(3n), so something similar to that.

Answer

Looks like a good use of the modulus operator! (Or, really, %)

let offset = 0 //modify to change where it starts
return (indexPath.row % 3 + offset) == 0 ? fullSize : normalSize