UITableView 单元格的动态高度问题 (Swift)

编程入门 行业动态 更新时间:2024-10-03 06:26:30
本文介绍了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)

本文发布于:2023-11-26 09:53:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633632.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单元格   高度   动态   UITableView   Swift

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!