gpt4 book ai didi

swift - Collection View 单元格动态高度问题

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

我想实现支持依赖于自动布局的单元格动态高度的collectionView。我有包含图像的产品单元格,其底部的堆栈 View 包含其价格和折扣价格以及产品报价将完成的计时器标签。有时产品没有报价,所以我需要从 stackView 隐藏计时器,然后单元格高度将会改变。我使用了这段代码

override func viewDidLoad() {
super.viewDidLoad()
homeCollection.delegate = self
homeCollection.dataSource = self
homeCollection.register(UINib(nibName: "ProductCell", bundle: Bundle.main), forCellWithReuseIdentifier: "cell")
(homeCollection.collectionViewLayout as! UICollectionViewFlowLayout).estimatedItemSize = UICollectionViewFlowLayoutAutomaticSize

}

然后为了在 cellForItemAtIndex 中进行测试,我使用了这段代码

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ProductCell
if indexPath.row == 0
{
cell.productTimerLabel.isHidden = true

}
return cell

}输出是这样的 enter image description here我的问题是为什么第一个单元格的顶部对齐方式比第二个单元格的顶部对齐方式更向下,我希望它们都具有相同的对齐方式

最佳答案

为此,您需要一个自定义 UICollectionViewLayout,因为 UICollectionViewFlowLayout 始终居中,而不是按照您想要的方式顶部对齐。

我建议您使用Aligned collection view flow layout我从 Github 使用的。它有一个属性,允许您使用 verticalAlignment = .top 进行顶部对齐

关于swift - Collection View 单元格动态高度问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50186139/

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