I am trying to replicate the AppStore Today's card view layout
Here is my code
extension TestViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 4
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let genericCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
if let label = genericCell.viewWithTag(100) as? UILabel {
label.text = "\(indexPath.item)"
}
return genericCell
}
}
extension TestViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 40
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cellHeight: CGFloat = 100
let numberOfItemsInRow = 2
let compressedWidth = collectionView.bounds.width / 2
let expandedWidth = compressedWidth * 0.5
let rowNumber = indexPath.item / numberOfItemsInRow
let isEvenRow = rowNumber % 2 == 0
let isFirstItem = indexPath.item % numberOfItemsInRow == 0
var width: CGFloat = 0.0
if isEvenRow {
width = isFirstItem ? expandedWidth : compressedWidth
} else {
width = isFirstItem ? compressedWidth : expandedWidth
}
return CGSize(width: width, height: cellHeight)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 20, left: 20, bottom: 0, right: 20)
}
}
Above code will work fine for odd number of dataSource. If it is even number, the last row of item will not have any white spacing in between.
The way that I use to overcome this problem is by adding additional 1 cell, with the automated width size but with 0 height.
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 4 + 1
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cellHeight: CGFloat = indexPath.item == collectionView.numberOfItems(inSection: 0) - 1 ? 0 : 100
}
However I don't think that this is the best approach to use. Can someone guide me on what to do?
What am I missing here? Thank you
