gpt4 book ai didi

ios - UICollectionViewLayout - 2 列 3 个单元

转载 作者:行者123 更新时间:2023-11-30 10:26:01 27 4
gpt4 key购买 nike

我正在尝试创建一个具有 7 单元格重复布局的 UICollectionView,如下所示:

enter image description here

但是,使用 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)
}

这就是结果:

enter image description here

我什至尝试对最后两个单元格使用较小的高度,以确保高度不是问题。感谢您的帮助。

<小时/>

更新我通过 UIStackViews 让它工作,尽管很烦人。

enter image description here

最佳答案

仅仅使用 UICollectionViewFlowLayoutsizeForItem 方法这并不是一件容易的事。你必须使用

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.
}

关于ios - UICollectionViewLayout - 2 列 3 个单元,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60044517/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com