在的UILabel与UITableViewCell中自动布局具有高度的错误 [英] UILabel in UITableViewCell with auto layout has wrong height

查看:377
本文介绍了在的UILabel与UITableViewCell中自动布局具有高度的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个的UITableView 与拥有100分的固定高度的细胞。在使用3约束针一的UILabel 的左侧,右侧和顶部边缘细胞的内容查看。因为我想要细胞的高度尽可能小标签的垂直紧靠优先设置为1000。

I have a UITableView with cells that have a fixed height of 100 points. The cells are created in a xib file that uses 3 constraints to pin a UILabel to the left, right and top edges of the cell's contentView. The label's vertical hugging priority is set to 1000 because I want the cell's height to be as small as possible.

当在XIB文件单元的宽度设定为320点,在相同的tableView的iPhone上,如预期自动布局工作宽度。然而,当我在单元格的宽度设置为小于320点,我得到意想不到的效果。 (我想使用tableViews具有不同的宽度相同的细胞中,例如在一个普遍的应用程序)

When the width of the cell in the xib file is set to 320 points, the same as the tableView's width on the iPhone, autolayout works as expected. However, when I set the width of the cell to less than 320 points, I get unexpected results. (I want to use the same cell in tableViews that have different widths, e.g. in a universal app)

例如:当我将宽度设置为224点,并给该标签在那个宽度占用2行的文本,标签的高度会增加,以适应2行,但是,当该单元被再调整为320点以适合于该宽度的的tableView,文本只占用1线,但标签的高度保持在2行。

For example: when I set the width to 224 points and give the label a text that takes up 2 lines at that width, the label's height will increase to fit the 2 lines, but when the cell is then resized to 320 points to fit in a tableView of that width, the text only takes up 1 line, but the height of the label remains at 2 lines.

我已经把一个示例项目在GitHub上演示该问题: https://github.com/bluecrowbar/CellLayout

I have put a sample project on GitHub to demonstrate the problem: https://github.com/bluecrowbar/CellLayout

有没有一种方法,使的UILabel 总是调整拥抱它的文字内容?

Is there a way to make the UILabel always resize to hug its text content?

推荐答案

在单元格添加子这个作品:

Adding this in the cell subclass works:

- (void)layoutSubviews
{
    [super layoutSubviews];
    [self.contentView layoutIfNeeded];
    self.myLabel.preferredMaxLayoutWidth = self.myLabel.frame.size.width;
}

我发现这对<一个href=\"http://useyourloaf.com/blog/2014/02/14/table-view-cells-with-varying-row-heights.html\">http://useyourloaf.com/blog/2014/02/14/table-view-cells-with-varying-row-heights.html.

更新1:的这个回答是iOS的7我发现表视图单元格自动布局是自iOS 8的非常不可靠的,即使是非常简单的布局。经过大量的实验,我(大部分)回去上工布局和细胞的高度人工计算。

Update 1: This answer was for iOS 7. I find auto layout in table view cells to be very unreliable since iOS 8, even for very simple layouts. After lots of experimentation, I (mostly) went back to doing manual layout and manual calculation of the cell's height.

更新2:的我已经运行在iOS 9一些测试,似乎 UITableViewAutomaticDimension 终于像宣传的那样。耶!

Update 2: I've run some tests on iOS 9 and it seems that UITableViewAutomaticDimension finally works as advertised. Yay!

这篇关于在的UILabel与UITableViewCell中自动布局具有高度的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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