0

I have a custom UICollectionViewFlowLayout which lays out items with a left-aligned format.

LAYOUT

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {

    var newAttributesArray = [UICollectionViewLayoutAttributes]()
    let superAttributesArray = super.layoutAttributesForElements(in: rect)!
    
    guard let attributesToReturn =  superAttributesArray.map( { $0.copy() }) as? [UICollectionViewLayoutAttributes] else {
        return nil
    }
    
    for (index, attributes) in attributesToReturn.enumerated() {
        if index == 0 || attributesToReturn[index - 1].frame.origin.y != attributes.frame.origin.y {
            attributes.frame.origin.x = sectionInset.left
        } else {
            let previousAttributes = attributesToReturn[index - 1]
            let previousFrameRight = previousAttributes.frame.origin.x + previousAttributes.frame.width
            attributes.frame.origin.x = previousFrameRight + minimumInteritemSpacing
        }
        newAttributesArray.append(attributes)
    }
    return attributesToReturn
}

When I reload a cell that is not the first in the horizontal line, the cell tried performs peculiarly is in the below illustration. I believe this is a layout issue. Reloading a cell that's first does not act this way.

behaviour of reloading cell

RELOAD METHOD

func selectedInterest(for cell: InterestCell) {
    guard let indexPath = mainView.collectionView.indexPath(for: cell),
          let documentID = cell.interest?.documentID,
          let isSaved = cell.interest?.isSaved else { return }
    var interest = self.interests[indexPath.item]
    interest.isSaved = !isSaved
    self.interests[indexPath.item] = interest

    self.mainView.collectionView.collectionViewLayout.invalidateLayout()
    self.mainView.collectionView.reloadItems(at: [indexPath])
}

I have tried to invalidate the layout before reloading however this has no effect.

David Henry
  • 1,972
  • 20
  • 43
  • Did you tried to just call `self.mainView.collectionView.reloadData()` instead of `invalidateLayout()` and `reloadItems`? – lpizzinidev Apr 02 '21 at 15:54
  • Just tied this, has no effect. My logic tells me somehow I need to get the layout attributes for the indexPath being reloaded and use that before I call the reload. But I could be wrong. – David Henry Apr 02 '21 at 16:57

0 Answers0