iOS UILabel 宽度不适合 table 单元格

iOS UILabel width doesn't fit inside table cell

我是 iOS 开发的新手。我在尝试将标签放入 uitableviewcell 时遇到问题。文本不断超出单元格。我添加了所有需要的约束,但它不起作用。 这是我的设置和代码:

Title label attributes: Number of lines-0, Line breaks-Word wrap

viewDidLoad():

self.tableView.estimatedRowHeight = 68.0;
self.tableView.rowHeight = UITableViewAutomaticDimension;

cellForRowAtIndexPath():

UILabel *titleLabel = (UILabel*)[cell viewWithTag:100];
titleLabel.text = @"Why does this long text get out of the cell? The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.";

我正在使用 xcode 6.2 和 ios 8.2。

感谢您的帮助。

截图:

细胞原型:

标题标签限制:

为了使文本保持在标签边界内和单元格中,您需要做两件事。

  1. 如果标签的宽度是固定的,那么在这种情况下,您的单元格的高度取决于标签的高度(从其内容派生)。正如您已经提供的 estimatedRowHeightrowHeight 作为 UITableViewAutomaticDimension。这样就可以了。
  2. 标签的宽度应该在到达单元格的最右边之前/直到它到达单元格的最右边。另外请确保如果标签的宽度是灵活的,那么它也应该从右侧钩住。

或者,您可以使用下面的 API 编写代码,根据标签的内容计算标签的高度。这将决定单元格的高度。最后在创建单元格时将文本分配给标签。

iOS 7 岁及以上:

#define LABELS_MAX_HEIGHT             10000.0f


CGSize constraintSize = CGSizeMake(label.frame.size.width, LABELS_MAX_HEIGHT);

NSAttributedString *attributedText = [[[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName: label.font}] autorelease];
        CGRect rect = [attributedText boundingRectWithSize:constraintSize
                                                   options:NSStringDrawingUsesLineFragmentOrigin
                                                   context:nil];
        strSize = rect.size;