我正在尝试创建一个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工作,虽然很烦人。

发布于 2020-02-03 18:11:56
通过使用UICollectionViewFlowLayout的sizeForItem方法,这将不是一项容易的任务。
if indexPath.row % 7 == 0 || indexPath.row % 7 == 4 {
return CGSize(width: collectionViewWidth, height: collectionViewWidth)
}然后在cellForItemAt方法中:
if indexPath.row % 7 == 4 {
// Provide a UIStackView with your required layout
// Or maybe even you could provide a smaller UICollectionView with just 3 cells, but that seems like overkill.
}https://stackoverflow.com/questions/60044517
复制相似问题