Swift UITableViewAutomaticDimension 不起作用 [英] Swift UITableViewAutomaticDimension is not working

查看:55
本文介绍了Swift UITableViewAutomaticDimension 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Swift 项目中有一张像这样的表

I have got a table in my Swift project like this

var tableView: UITableView! 
tableView = UITableView()
tableView.dataSource = self
tableView.delegate = self
tableView.rowHeight = UITableViewAutomaticDimension       
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return postTexts.count
    }      
  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 250;
   }

  func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
       return 5
   }

我希望我的 tableview 的高度是自动的,因此我使用了UITableViewAutomaticDimension,但它仍然显示近一半的单元格宽度

I wanted my tableview's height to be automatic thus i used UITableViewAutomaticDimension,but it is still showing nearly half of the cells width

推荐答案

您必须删除 -heightForRow 方法并在 table view 上设置 estimatedRowHeight.
estimatedRowHeight 用于计算 TV 的 bar 大小等,因此它应该是一个尽可能接近 table view cell 高度平均大小的真实值.
现在,如果您使用自动布局并且正确设置了约束,您应该会看到 UITableViewCell 的正确调整大小.要正确设置 TVC 内的约束,您应该考虑以一种可以控制单元格大小的方式放置它们.
例如,假设您的 TVC 只有一个标签,并且该标签有 4 个附加到其超视图的约束:顶部、底部、尾随和前导,具有固定的恒定大小.UILabel 实例还将 numberOfLines 设置为 0(意味着它可以扩展以填充您的所有文本).
当自动布局引擎开始请求标签内在内容大小时,标签将返回一个适合您所有文本的值,超级视图大小将根据此更改大小.
如果像以前一样将 TVC 固定到特定高度,则 TVC 无法自行展开.

You must delete the -heightForRow method and set on the table view an estimatedRowHeight.
The estimatedRowHeight is used to calculate the bar size etc of the TV, so it should be a real value closest as possible to an average size of the table view cell height.
Now, if you are using auto layout and constraints are set correctly you should see a correct resize of your UITableViewCell. To set correctly the constraints inside the TVC you should think to place them in a way that they can control the size of your cell.
For instance say that your TVC has just one label and that label has 4 constraints attached to its superview: top, bottom, trailing and leading with a fixed constant size. The UILabel instance has also the numberOfLines set to 0 (means that it can expand to fill all your text).
When the autolayout engine starts to request the label intrinsicContentSize, the label will return a value that will fit all your text, the superview size will change the size according to that.
If you fix the TVC to a specific height as you did before, the TVC can't expand itself.

这篇关于Swift UITableViewAutomaticDimension 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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