【发布时间】:2020-02-03 17:45:39
【问题描述】:
我正在尝试创建一个具有 7 单元重复布局的 UICollectionView,如下所示:
但是,使用 CollectionViewLayout,我似乎无法将第 6 和第 7 个单元格放入同一列。
以下是相关代码:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let collectionViewWidth = self.collectionView.bounds.width
let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
let spaceBetweenCells = flowLayout.minimumInteritemSpacing
var adjustedWidth = collectionViewWidth - spaceBetweenCells
if indexPath.row % 7 == 0 {
return CGSize(width: collectionViewWidth, height: collectionViewWidth)
}
if indexPath.row % 7 == 1 || indexPath.row % 7 == 2 || indexPath.row % 7 == 3 {
adjustedWidth = collectionViewWidth - (spaceBetweenCells * 2)
return CGSize(width: floor(adjustedWidth / 3), height: floor(adjustedWidth / 3))
}
if indexPath.row % 7 == 4 {
adjustedWidth = collectionViewWidth - spaceBetweenCells * 2
return CGSize(width: floor(adjustedWidth / 3) * 2 + spaceBetweenCells, height: floor(adjustedWidth / 3) * 2 + spaceBetweenCells)
}
if indexPath.row % 7 == 5 || indexPath.row % 7 == 6 {
adjustedWidth = collectionViewWidth - spaceBetweenCells * 2
return CGSize(width: floor(adjustedWidth / 3), height: floor(adjustedWidth / 3))
}
let width: CGFloat = adjustedWidth / 2
let height: CGFloat = width;
return CGSize(width: width, height: height)
}
结果如下:
我什至尝试为最后两个单元格使用较小的高度,以确保高度不是问题。感谢您的帮助。
更新 我通过 UIStackViews 让它工作了,虽然很烦人。
【问题讨论】:
-
为什么不用 UIStackView?为集合视图中的每个项目提供大小似乎很痛苦。
-
您的意思是使用 UIStackViews 的组合而不是 UICollectionView?我必须管理视图的入队/出队,那么不是吗?这似乎更痛苦。
-
我的意思是两者的结合。
标签: ios swift uicollectionview uikit uicollectionviewlayout