如何为 UITableView 提供动态高度 [英] How to give dynamic height to UITableView

查看:27
本文介绍了如何为 UITableView 提供动态高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码中有一个 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 一个动态高度.我尝试了两件事

And i want to give a dynamic height to this UITableView.I tried two things

   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 对象中正确固定前导、尾随、顶部和底部约束.

The issue could be your autolayout constraint which does not seems to be proper. So you need to make sure that you have pinned leading, trailing, top and bottom constraint properly inside your tableViewCell objects.

注意:- 如果您使用 UILabel,则设置行数 = 0.

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

这篇关于如何为 UITableView 提供动态高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆