gpt4 book ai didi

ios - 渲染后更新单元格高度

转载 作者:搜寻专家 更新时间:2023-11-01 07:14:01 24 4
gpt4 key购买 nike

我已经设置了一个 UITableViewCellUITableViewAutomaticDimension
TableViewCell 中嵌入了一个 UICollectionView,它不可滚动,但可以根据 collectionview 的内容具有可变高度。

现在我尝试的是渲染单元格并将 collectionview 的高度约束分配给变量 collectionViewHeightConstraint 然后在 layoutSubviews 方法中渲染 collectionview 后更新高度

override func layoutSubviews() {
super.layoutSubviews()
self.collectionViewHeightConstraint?.constant = self.collectionView!.contentSize.height
}

这是 collectionview 约束的样子(使用制图):

    self.contentView.addSubview(self.collectionview)   
self.contentView.addSubview(self.holdingView)
constrain(self.holdingView!, self.contentView) {
holderView, container in
holderView.top == container.top
holderView.left == container.left
holderView.right == container.right
holderView.bottom == container.bottom
}
constrain(self.collectionView!, self.holdingView) {
collectionView, containerView in
collectionView.top == containerView.top
collectionView.left == containerView.left
collectionView.right == containerView.right
collectionViewHeightConstraint = collectionView.height == collectionViewHeight
containerView.bottom == collectionView.bottom
}

但这似乎并没有更新单元格高度。

有什么方法可以更新吗?

编辑
这不是某些人建议的重复问题,原因在下面的评论中有解释。

最佳答案

由于评论空间太小,我把所有的都放在这里:

注意:您实际上不必在 viewDidLayoutSubviews 中设置高度限制,只需在您可以确定 UICollectionView设置您的布局已在整个屏幕上正确设置!例如,在 viewDidAppear 中执行此操作,然后调用 layoutIfNeeded() 也可以。将它移动到 viewDidAppear 只有在调用 viewDidAppear 之前设置了 UICollectionView 才会起作用,即你知道你的 UICollectionView数据源。

修复 1:

在设置高度并检查 heightConstant != contentSize 后尝试重新加载 UITableView。使用它来检查 UICollectionView 的高度是否正确更新,即:

override func layoutSubviews() {
super.layoutSubviews()

if self.collectionViewHeightConstraint?.constant != self.collectionView!.contentSize.height{

self.collectionViewHeightConstraint?.constant = self.collectionView!.contentSize.height

//to make sure height is recalculated
tableView.reloadData()
//or reload just the row depending on use case and if you know the index of the row to reload :)
}
}

我同意你的评论,它很乱,我的意思是用它来解决问题和/或检查这是否是问题所在!

至于为什么是0,可能是因为你的UICollectionView还没有设置(cellForItem还没有被调用)所以contentSize 实际上不是计算出来的!

修复 2:

一旦为 UICollectionView 设置了 dataSource,即您收到数据,您就可以计算 UICollectionView contentSize 的高度手动设置一次并重新加载该行。如果计算是一项繁琐的工作,只需设置数据源并在 UICollectionView 上调用 reloadData。这将确保 UICollectionView 设置正确,然后将单元格的约束设置为 contentSize 并调用 reloadDatareloadRowUITableView 上。

UICollectionView 设置并且您的 View 布局之后,您基本上可以随时设置 heightConstraint。您只需要在之后调用 tableView.reloadData()

关于ios - 渲染后更新单元格高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43255991/

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