gpt4 book ai didi

swift - 如何为 UITableView 提供动态高度

转载 作者:行者123 更新时间:2023-11-30 12:14:59 26 4
gpt4 key购买 nike

我的代码中有一个 UITableView

tableView = UITableView(frame: CGRect(x:0,y:0,width:0,height:0))
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellReuseIdentifier")
tableView.delegate = self
tableView.dataSource = self
tableView.translatesAutoresizingMaskIntoConstraints = false
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return comments.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier") as UITableViewCell!

cell.textLabel?.text = self.comments[indexPath.row]
return cell
}

我想给这个 UITableView 一个动态高度。我尝试了两件事

   tableView.estimatedRowHeight = 88.0
tableView.rowHeight = UITableViewAutomaticDimension

tableView.heightAnchor.constraint(equalToConstant: tableView.contentSize.height).isActive = true

但它们都不起作用。

最佳答案

设置UITableViewAutomaticDimension后,您不需要使用以下代码行

tableView.heightAnchor.constraint(equalToConstant: tableView.contentSize.height).isActive = true

问题可能是您的 autolayout 约束似乎不正确。因此,您需要确保在 tableViewCell 对象内正确固定前导、尾随、顶部和底部约束。

Note:- If you are using UILabel then set number of lines = 0.

关于swift - 如何为 UITableView 提供动态高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45541542/

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