如何根据文本标签长度动态设置表格单元格高度? [英] how to set table cell height dynamically depending on text label length?

查看:140
本文介绍了如何根据文本标签长度动态设置表格单元格高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习Obj-C和iOS编程,但我还是很新。我决定尝试制作一个简单的Reddit客户端应用程序。我试图在 UITableView 中显示首页帖子,每个帖子由其自己的单元格表示。

I am trying to learn Obj-C and iOS programming, but am still very new. I decided to try and make a simple Reddit client application. I am trying to display the front page posts within a UITableView, with each post represented by its own cell.

在单元格上,这是我设置标题的方式:

On the cell, here is how I am setting the title:

cell.textLabel.numberOfLines = 0;
cell.textLabel.text = [[tempDictionary objectForKey:@"data"] objectForKey:@"title"];   
[cell.textLabel sizeToFit];

但是,如果标题文本太长,单元格最终会自行剪裁。这是一张图片:

However, the cell ends up clipping itself if the title text is too long. Here's a picture:

如何让我的单元格自动调整高度以适应更长的标题标签,而不会与其他单元格或详细文本标签相交?

How can I make my cells automatically adjust their heights to accommodate longer title labels, without intersecting other cells or the detail text label?

感谢您的帮助!

推荐答案

对于新的iOS 8,有一种新方法可以实现这一点。

For new iOS 8 there is a new way to make this simple.

有一个新参数可根据您的自动布局约束计算单元格高度。这是 UITableViewAutomaticDimension 。您可以在视图控制器的 viewWillAppear 方法中使用它。

There is new a parameter that calculates your cell height with respect of your auto layout constraints. This is UITableViewAutomaticDimension. You can use it in the viewWillAppear method of your view controller.

目标C:

- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];
  self.tableView.estimatedRowHeight = 70.0; // for example. Set your average height 
  self.tableView.rowHeight = UITableViewAutomaticDimension;
  [self.tableView reloadData];
}

Swift:

override func viewWillAppear(animated: Bool) {
    self.tableView.estimatedRowHeight = 70 // for example. Set your average height 
    self.tableView.rowHeight = UITableViewAutomaticDimension
    self.tableView.reloadData()

} 

工作得很好,就像你想要的那样。至于我,我在 viewDidLoad 中添加高度的东西,并在 viewWillAppear 中只留下reloadData()。 来源也很有用。

Work nice and as you want at your example. As for me, I add height things in viewDidLoad and left in viewWillAppear only reloadData(). There is also useful source.

来自文档: rowHeight的默认值是UITableViewAutomaticDimension。我现在保留代码,但是请记住,您不需要在iOS 8 +中设置行高。

From documentation: The default value of rowHeight is UITableViewAutomaticDimension. I leave the code as it is, for now, but keep in mind that you don't need to set row height in iOS 8+.

您需要做的主要是明确设置所有约束,例如到领先,尾随,顶部和底部。首先尝试一下,不要在上面添加任何代码行。

The main thing you need to do is to set all constraints explicitly e.g. to the leading, trailing, top and bottom. Try it first, without adding any lines of code above.

这篇关于如何根据文本标签长度动态设置表格单元格高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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