gpt4 book ai didi

ios - UITableView 的动态高度(不是 Cell)

转载 作者:搜寻专家 更新时间:2023-10-31 22:29:50 25 4
gpt4 key购买 nike

我正在尝试使用 UITableView 列出用户可用的所有不同 HomeKit 设备。

显然没有办法知道他们有多少台设备,所以我需要更改 Storyboard 中的 UITableView 高度。

我试过这个,我在 viewDidLoad() 函数中调用它:

func adjustHeightOfTableView() {

//getting the height of the tableview
var tableHeight = self.tableView.contentSize.height

//the height of the content inside the view
var maxHeight = self.tableView.superview?.frame.size.height


//if the height of the content is bigger then the height of the tableview
if (maxHeight! > tableHeight) {

tableHeight = maxHeight!
//set the tableview height to be the content height

}

//trying to reload the tableview height?
self.view.layoutIfNeeded()
self.tableView.reloadData()

}

我想在 tableview 下放置一些 UI 元素,我希望它们是从 tableview 底部开始的一个固定空间,但也让 tableview 成为它需要的高度,无论单元格数量是多少有。

但这就是行不通。如果我做错了什么,或者如果有人知道如何进行这项工作,请告诉我。谢谢!

最佳答案

注意:对于这种方法,您需要有静态单元格高度或想出一种方法来事先知道内容大小的总高度是多少

假设您正在使用约束,请在您的 UITableView 上创建以下约束(除了前导和尾随!)

将优先级为 750 的高度约束和底部间距约束为 0 添加到您的 super View ,这将是 >= 0 并且优先级为 1000。为此高度约束创建导出您在 UIViewController

中创建

现在,

func adjustHeightOfTableView() {

//set the height to be equal to the number of elements multiplied by the height of each cell.
//or use some logic that allows you to know what content size or space the cells will occupy!
tableViewHeightConstraint.constant = dataArray.count * rowHeight

view.layoutIfNeeded()
}

现在,如果您的 UITableView 高度小于 super View ,没问题!但如果它大于屏幕边界,它将打破高度限制并变为全屏并正常显示内容,就像您期望的 UITableView 一样!

编辑:即使您使用的是 UIAutomaticRowDimensions,您也可以通过编程方式向 UITableView 添加约束。即

当然,您的所有其他 View 仍然对您的 UITableView 有底部约束。在您的 Storyboard 中创建一个 UITableView,其中包含 super View 的正常前导、尾随、顶部和底部。获取数据。获取 UITableView 的 contentSize,然后移除底部约束。现在添加一个高度约束,它将是您的 UIScreen.main().bounds.size.heightcontentSize 的最小值。

关于ios - UITableView 的动态高度(不是 Cell),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40778186/

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