我已经设置了一个UITableViewCell和UITableViewAutomaticDimension
TableViewCell中嵌入了一个UICollectionView,它不能滚动,但可以根据集合视图的内容具有可变的高度。
现在,我尝试的是呈现单元格,并将集合视图的高度约束赋值给变量collectionViewHeightConstraint,然后在layoutSubviews方法中呈现集合视图后更新高度
override func layoutSubviews() {
super.layoutSubviews()
self.collectionViewHeightConstraint?.constant = self.collectionView!.contentSize.height
}这就是集合视图约束的样子(使用地图学):
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
}但这似乎并没有更新单元格的高度。
有什么方法可以更新吗?
编辑
这不是一个重复的问题,这是一个重复的问题,并解释了为什么是在下面的评论。
发布于 2017-04-06 16:33:12
由于评论篇幅太小,我将把所有内容放在这里:
注意:,您实际上不必在viewDidLayoutSubviews中设置高度约束,您可以确保UICollectionView已经设置好和,您的布局已经在整个屏幕上正确设置了!例如,在viewDidAppear中执行该操作,然后调用layoutIfNeeded()也可以。只有在调用viewDidAppear之前已经安装了UICollectionView,即预先知道UICollectionView dataSource,才能将其移动到viewDidAppear中。
图1:
在设置高度并检查UITableView是否为heightConstant != contentSize之后,尝试重新加载heightConstant != contentSize。使用此方法检查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的UICollectionView,即收到数据,就可以计算UICollectionView contentSize手动拥有的高度,并将其设置一次,然后重新加载行。如果计算是一项繁琐的任务,只需设置dataSource并在UICollectionView上调用reloadData即可。这将确保正确设置UICollectionView,然后将单元格的约束设置为contentSize,并在UITableView上调用reloadData或reloadRow。
您基本上可以在您的heightConstraint设置好之后的任何时候设置和,您的视图已经布置好了。你只需要在事后打电话给tableView.reloadData()。
发布于 2017-04-06 13:16:47
您可以重新加载tableview的特定单元格。
let indexPath = IndexPath(item: rowNumber, section: 0)
tableView.reloadRows(at: [indexPath], with: .top)发布于 2017-04-06 13:36:55
按照您的要求,我想如果我们先加载集合视图,然后用集合视图的正确高度加载表视图,我们可以解决这个问题。
collectionView.reloadData()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.collectionViewHeightConstraint?.constant = self.collectionView!.contentSize.height
})
tableview.reloadData()这样,当表视图加载时,单元格具有基于集合视图内容大小的所需高度。
https://stackoverflow.com/questions/43255991
复制相似问题