0

I'm making a custom UICollectionViewLayout class for practice, essentially trying to reproduce the horizontal flow layout where cells are laid out horizontally infinitely.

Everything was working perfectly with my prepare() and layoutAttributesForElements() functions looking like this:

override func prepare() {
    cache.removeAll(keepingCapacity: false)

    var frame = CGRect.zero

    for item in 0..<numberOfItems {
        let indexPath = IndexPath(item: item, section: 0)
        let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
        frame = CGRect(x: CGFloat(item) * width + CGFloat(item) * spacing, y: 0, width: width, height: height)
        attributes.frame = frame
        cache.append(attributes)
    }
}

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
    var layoutAttributes = [UICollectionViewLayoutAttributes]()
    for attributes in cache {
        if attributes.frame.intersects(rect) {
            layoutAttributes.append(attributes)
        }
    }
    return layoutAttributes
}

The problem arises when I try to add an inset of value spacing to the x coordinate in following line in prepare() so that the first cell in the collection view has a leftwards inset:

frame = CGRect(x: CGFloat(item) * width + CGFloat(item) * spacing, y: 0, width: width, height: height)

As soon as I do, everything looks well and good until I try swiping through the collection view. The following exception is thrown:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'no UICollectionViewLayoutAttributes instance for -layoutAttributesForItemAtIndexPath: <NSIndexPath: 0x618000036060> {length = 2, path = 0 - 3}'

Would someone please explain why this is happening? Is there an alternative way of achieving the layout?

cyril
  • 3,020
  • 6
  • 36
  • 61

1 Answers1

0

Found the solution! Apparently overriding layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? fixes the issue! But I have no idea why.

cyril
  • 3,020
  • 6
  • 36
  • 61