Я пытаюсь скопировать AppStore. Сегодняшний макет представления карты
Вот мой код
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)
}
}
Приведенный выше код будет работать нормально для нечетного числа источника данных. Если это четное число, последний ряд элемента не будет иметь никакого белого интервала между ними.
Способ, который я использую для решения этой проблемы, заключается в добавлении дополнительной 1 ячейки с автоматическим размером ширины, но с 0 высотой.
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
}
Однако я не думаю, что это лучший подход для использования. Кто-нибудь может подсказать мне, что делать? Что мне здесь не хватает? Спасибо