ios - 根据 ScrollView 上的内容增加表格 View 高度

标签 ios swift uitableview uiscrollview uikit

您好,我想在 ScrollView 上动态增加表格 View 的高度。 我会尝试下面的代码,即使它不起作用

这里items是tableview数据数组

override func viewDidLoad() {
    super.viewDidLoad()
    rewardPointsApi()
    if(items != nil) {
        self.tableviewheight.constant = CGFloat(70*items.count)
    }
    tableviewheight.constant = tableview.contentSize.height
}

最佳答案

有时用 tableview 的内容大小设置常量不会正确更新高度,因为 tableview 正在重新加载或自行计算

什么地方最好?

如果你有静态数据那么可能是viewDidAppear是最好的地方

 override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.view.layoutIfNeeded()
        self.heightConstraint.constant = self.tableView.contentSize.height
        self.view.layoutIfNeeded()

  }

如果您的数据是动态的,例如调用 API。然后在主队列内的响应 block 内。

DispatchQueue.main.async {
        self.tableView.reloadData()
        self.view.layoutIfNeeded()
        self.heightConstraint.constant = self.tableView.contentSize.height 
        self.view.layoutIfNeeded()
 }

重要:与内容大小直接相关的因素是 estimateRowHeight所以如果你确定你的单元格的高度那么你直接申请静态行数

希望对遇到同样问题的你和其他人有所帮助

关于ios - 根据 ScrollView 上的内容增加表格 View 高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55026820/

相关文章:

ios - 在应用程序中启动不同的 ios 应用程序

ios - 为什么 NSMutableData 改变指针的地址?

iphone - 清除 UITableViewCell 的背景颜色?

ios - SegmentedControl 隐藏和显示 TableView 单元格

ios - 将标题添加到 CSV 文件

ios - 在 iOS 上,可以在主线程之外读取 UI 吗?

objective-c - 是否可以使用 KVO 来观察 CLLocation 对象?

ios - 异步获取 Swift Xcode

swift - 在 Swift 中使用带有 CocoaPods 的静态库对于 Realm 失败

iOS - TableView 错误