0

I wonder why my UICollectionView reorder the cells if not fit within CollectionView's width.

After adding the long "XXXXX.." The "Super" cell moved to the right.

p.s After some reading I've found that the issue may be in "minimumInteritemSpacing" as according to its documentation.

...after the number of items is determined, the actual spacing may possibly be adjusted upward.

This is how I set up my layout

// 2 - setup flowlayout
    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    layout.minimumLineSpacing = self.tagSpacing
    layout.minimumInteritemSpacing = self.tagSpacing
    layout.estimatedItemSize = UICollectionViewFlowLayoutAutomaticSize
    layout.scrollDirection = .vertical
Elsammak
  • 1,102
  • 10
  • 26
  • The layout of the collection view is defined by the `UICollectionViewLayout` implementation that you set on your collectionView. You'll have to show us your implementation of the `UICollectionViewLayout` (e.g., show if you use `UICollectionViewFlowLayout` or your own custom implementation) – Milan Nosáľ Jan 17 '18 at 05:59
  • @MilanNosáľ Done! – Elsammak Jan 17 '18 at 06:04

2 Answers2

0

The answer was to define my own layout.

import UIKit

class CustomViewFlowLayout : UICollectionViewFlowLayout {

let cellSpacing:CGFloat = 0

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
    if let attributes = super.layoutAttributesForElements(in: rect) {
        for (index, attribute) in attributes.enumerated() {
            if index == 0 { continue }
            let prevLayoutAttributes = attributes[index - 1]
            let origin = prevLayoutAttributes.frame.maxX
            if(origin + cellSpacing + attribute.frame.size.width < self.collectionViewContentSize.width) {
                attribute.frame.origin.x = origin + cellSpacing
            }
        }
        return attributes
    }
    return nil
}
}

Thanks to this answer here

Elsammak
  • 1,102
  • 10
  • 26
0

UICollectionViewFlowLayout supports variable sizes of cells, but it aligns the cells as "justified". In your case as you add a new cell that does not fit on the first row, the layout justifies the first row (making it span across the whole row) - so basically it puts the first cell to the left and the second one to the right. And then it continues with the next row. That's the explanation of whats going on.

I guess you want a left aligned flow. However, as far as I know UICollectionViewFlowLayout does not support that. To achieve what you want, either use some 3rd party library (e.g., UICollectionViewLeftAlignedLayout), or go over the answers here and implement your own layout.

Milan Nosáľ
  • 19,169
  • 4
  • 55
  • 90