Search code examples
swiftuser-interfacelayoutcollectionview

How do I achieve this zig-zag collection view layout?


Here's how I want the cells to look like , Here's how I want the cells to look like

I'm doing indexPath.row % 3 == 0 but that doesn't work unfortunately.


Solution

  • It has nothing to do with the collection view layout, it is about how do you want to display the cell.

    I would suggest to do this logic in collectionView(_:willDisplay:forItemAt:) as follows:

    Assuming that your view controller conforms to UICollectionViewDelegate:

    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        cell.backgroundColor = [.purple, .white, .white, .purple][indexPath.item % 4]
    }
    

    Thanks to @vacawama for elegant edit ([.purple, .white, .white, .purple][indexPath.item % 4]).