UITableView 单元格的动态高度问题 (Swift) [英] Dynamic Height Issue for UITableView Cells (Swift)

查看:46
本文介绍了UITableView 单元格的动态高度问题 (Swift)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可变长度的文本数据被注入到 tableview 单元格标签中.为了让每个单元格的高度都合适,我在 viewDidLoad() 中实现了:

Text data of variable length are being injected into tableview cell labels. In order for each cell height to be properly sized, I have implemented in viewDidLoad():

self.tableView.estimatedRowHeight = 88.0
self.tableView.rowHeight = UITableViewAutomaticDimension

这估计高度为 88.0 像素,如果更大,应自动调整高度.它适用于尚未滚动到的单元格(因为在滚动单元格时调用了UITableViewAutomaticDimention),但不适用于单元格在加载包含数据的表格时最初呈现在屏幕上.

This estimates the height to be 88.0 pixels and should resize the height automatically if larger. It works perfectly for cells that have yet to be scrolled to (as UITableViewAutomaticDimention is called upon scrolling to the cell), but not for the cells that are initially rendered onscreen upon loading the table with data.

我尝试重新加载数据(如许多其他资源中所建议的那样):

I have tried reloading the data (as suggested in many other resources):

self.tableView.reloadData()

viewDidAppear()viewWillAppear() 中都没有帮助.我迷路了.. 有谁知道如何为最初加载到屏幕上的单元格渲染动态高度?

in both viewDidAppear() and viewWillAppear() and it did not help. I am lost.. does anyone know how to render the dynamic height for the cells loaded initially on screen?

推荐答案

试试这个:

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

编辑

func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

Swift 4

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

Swift 4.2

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableView.automaticDimension
}

定义上述两种方法.
它解决了问题.

Define above Both Methods.
It solves the problem.

PS:需要顶部和底部约束才能工作.

这里是示例

这篇关于UITableView 单元格的动态高度问题 (Swift)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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