I wanted to make indefinite UICollectionViewCell
that moves to another row once it’s exceed the width of my UICollectionView
. Here’s the picture of what I’m trying to achieve.
As you can see, each width of the cell is resizing based on the content inside. The next cell will go horizontally, then after that it create another row if it exceed the width.
Here’s my UICollectionView
:
var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.backgroundColor = .white
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.backgroundColor = MSColorFoundation.msClear
return collectionView
}()
Here’s my UICollectionViewLayoutDelegate:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let noOfCellsInRow = 3
let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout
let totalSpace = (flowLayout?.sectionInset.left ?? 0.0)
+ (flowLayout?.sectionInset.right ?? 0.0)
+ ((flowLayout?.minimumInteritemSpacing ?? 0.0) * CGFloat(noOfCellsInRow - 1))
let size = Int((collectionView.bounds.width - totalSpace) / CGFloat(noOfCellsInRow))
return CGSize(width: size, height: 60)
}
2
Answers
From what I can see in your code, the
sizeForItemAt
function will always create cells in a way that your collection view will always have 3 cells in a row. I would suggest you to omit yoursizeForItemAt
function and create a simple Xib cell. Take a label in you Xib and then give your label a leading and trailing constant then register that Xib to your collection view. This will make your every cell to automatically depend on its label and infer its width from its label.It sounds like you want to implement a UICollectionView with cells that flow from left to right, wrapping to the next row when they exceed the width of the collection view. This can be achieved using the UICollectionViewFlowLayout, which is a built-in layout class provided by UIKit.
To create a UICollectionViewFlowLayout that flows cells from left to right and wraps to the next row, you can set the scroll direction to horizontal and adjust the minimumInteritemSpacing and minimumLineSpacing properties as needed.
In your custom UICollectionViewCell subclass, you can set the autoresizingMask property to allow the cell to resize itself as needed when the collection view width changes