ios - 在 ScrollView 中设置 ContentView 高度以动态更改

标签 ios swift autolayout

我已经为此苦苦挣扎了好几天,希望有人可以提供帮助。

我的结构看起来像这样:

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 ,以及当我 retrieveDataretrieveImages FromFirebase 时:

func configureTableView() {

    self.postTableHeightConstraint.constant = postTableView.contentSize.height

    postTableView.reloadData()
    postTableView.layoutSubviews()
    postTableView.layoutIfNeeded()

}

我的自动布局设置正确,因为一切都滚动并且看起来正确,但由于某种原因它没有创建足够的滚动区域,就好像它只加载了大约 75% 的所需可滚动空间我的内容 View 。

就好像它用我在 Interface Builder 中设置为占位符的值覆盖了在 viewDidLayoutSubViews 中计算的值

我已经尝试过所有这些:

  1. 设置 contentViewheightConstraint = contentRect.height
  2. 设置 scrollViewheightConstraint = contentRect.height
  3. 设置tableViewheightConstraint = contentRect.height
  4. 尝试了上述方法的组合

似乎没有人工作,我错过了什么?

最佳答案

为了解决这个问题,我将 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/

相关文章:

iphone - ECSlidingViewController 推送数据到 TableView

ios - 如何在 Swift 3 中多次触摸 UICollectionViewCells

swift - 在 SwiftUI 中有条件地使用 View

ios - 当出现调用或热点状态栏时,我的应用程序布局被破坏

jquery - Html5 音频无法在 Cordova App 中播放

ios - 当玩家 "Remove"一场比赛正在进行时如何从 GKTurnBasedMatchmakerViewController 获得通知

ios - 当使用自动布局时 View 没有约束时会发生什么?

iOS 自动布局和拥抱内容

ios - 可以在不使用 StoryBoard 的情况下执行 segue 吗?

ios - Swift - 在保持 api 清晰度的同时传播错误