我已经为此苦苦挣扎了好几天,希望有人可以提供帮助。
我的结构看起来像这样:
UIView
|---UIScrollView
|---UIContentView
|---UIHeaderView
|---UITableView
|---UITCollectionView
我在 Interface Builder 中将我的高度和约束设置为 0(出于测试目的,我也厌倦了将其设置为 3600),并且然后我运行一个 for 循环来获取 UIContentView 中所有 View 的高度在加载所有 subview 后:
override func viewDidLayoutSubviews() {
var contentRect = CGRect.zero
for view in contentView.subviews {
contentRect = contentRect.union(view.frame)
}
contentHeightConstraint.constant = contentRect.height
}
我还调用了一个方法来重新加载表并更新 cellForRowAt indexPath 处的 subview ,以及当我 retrieveData 和 retrieveImages FromFirebase 时:
func configureTableView() {
self.postTableHeightConstraint.constant = postTableView.contentSize.height
postTableView.reloadData()
postTableView.layoutSubviews()
postTableView.layoutIfNeeded()
}
我的自动布局设置正确,因为一切都滚动并且看起来正确,但由于某种原因它没有创建足够的滚动区域,就好像它只加载了大约 75% 的所需可滚动空间我的内容 View 。
就好像它用我在 Interface Builder 中设置为占位符的值覆盖了在 viewDidLayoutSubViews 中计算的值
我已经尝试过所有这些:
- 设置 contentView 的 heightConstraint = contentRect.height
- 设置 scrollView 的 heightConstraint = contentRect.height
- 设置tableView的heightConstraint = contentRect.height
- 尝试了上述方法的组合
似乎没有人工作,我错过了什么?
最佳答案
为了解决这个问题,我将 viewDidLayoutSubviews() 代码移动到一个新的自定义方法中,并在每次完成 configureTableView() 方法时调用它
func calcTotalHeight() {
for view in contentView.subviews {
self.contentRect = self.contentRect.union(view.frame)
}
contentHeightConstraint.constant = self.contentRect.height
contentView.needsUpdateConstraints()
}
func configureTableView() {
//1. Set Table Row dimensions
postTableView.rowHeight = UITableViewAutomaticDimension
postTableView.estimatedRowHeight = 375
//2. Update Table View and reload contentview
postTableView.reloadData()
contentView.layoutIfNeeded()
//3. Update Table View Height
self.postTableHeightConstraint.constant = postTableView.contentSize.height
//4. Reload ContentView and Recalculate New Height of Content View
contentView.layoutSubviews()
calcTotalHeight()
}
这不是最有说服力的解决方案,但它有效,并且不会在加载时产生太多开销。
此外,重要需要指出的是,reloadData、layoutIfNeeded 和 layoutSubviews 相对于其他代码的顺序在使其正常工作方面发挥着关键作用。
关于ios - 在 ScrollView 中设置 ContentView 高度以动态更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52264048/