gpt4 book ai didi

ios - 自动布局为每个 collectionViewCell 计算相同的高度

转载 作者:行者123 更新时间:2023-11-29 01:16:20 31 4
gpt4 key购买 nike

所以我有一个 Collection View ,它使用我在 Github 上找到的自定义布局,名为 CHTCollectionViewWaterfallLayout到目前为止我喜欢它,但是我希望使自定义 Collection View 单元格的高度动态化,但我无法连接自动布局来计算它。我在 Github 上分享了一个生成随机字符串大小并显示它们的简单示例项目,唯一的问题是自动布局为每个 Collection View Cell 生成相同的单元格高度。该项目可以找到here .

为了让您了解我的思考过程,我使用 CHTCollectionViewDelegateWaterfallLayout sizeForItemAtIndexPath 方法计算单元格高度。由于我还使用委托(delegate)方法 columnCountforSection 我的想法是,因为我根据方向提供了有限数量的列,所以我采用 collectionView 框架宽度,然后除以列数得到我的宽度对于细胞。

enter image description here

   func collectionView (collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
{
var cell = dict["heightCell"] as? CollectionViewCell

let randomString = RadomStrings[indexPath.item]

let float = CGFloat(columnCount)
let width = collectionView.bounds.size.width / float
if cell == nil {
cell = NSBundle.mainBundle().loadNibNamed("CollectionViewCell", owner: self, options: nil)[0] as? CollectionViewCell
dict["heightCell"] = cell
}
cell?.RandomStringLabel.text = randomString
cell!.frame = CGRectMake(0, 0, CGRectGetWidth(collectionView.bounds), CGRectGetHeight(cell!.frame))
cell!.setNeedsLayout()
cell!.layoutIfNeeded()
var size = cell?.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
size?.width = width
return CGSize(width: width, height: size!.height)
}

我的约束非常基本。我对每个轴都有约束。一个位于内容 View 的顶部,前导、尾随和底部。我在标签上也有一个大于等于45的高度。

使用自动布局计算 TableViewCell 的高度对我来说很容易,我喜欢它,因为我喜欢这种高度计算方法背后的 DRY 原则。所以我想在我的应用程序中保持这个高度计算过程相同。 CollectionViews 对我来说是一个相对较新的布局过程,所以我很想了解我在这里做错了什么。希望我对每个人都清楚,谢谢!

最佳答案

我想通了!我没有做的是对我创建的自定义单元格设置宽度限制!呸!

关于ios - 自动布局为每个 collectionViewCell 计算相同的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35134078/

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