UILabel文本填充的ios autolayout问题

时间:2014-02-25 18:20:51

标签: ios iphone objective-c uilabel autolayout

我为自己的表视图创建了自定义单元格的自定义类。有消息的UILabel。我正在使用故事板来设置约束,将标签固定到表格单元格的顶部和右侧,我发现这样做会导致标签调整大小以适应内容。现在我无法弄清楚如何向标签添加填充,因为在选择自动布局后,在cellForRowAtIndexPath中完成的任何操作都不起作用。我已经看过很多用CGRectMake做浮点值的例子,但它们不起作用,我认为这是因为自动布局。对此有什么解决方案吗?

我甚至不确定要为此展示什么代码...所以这里有一些东西:

我如何获得消息的高度...单元格设置为220宽... cellForRowAtIndexPath:

static NSString *cellIdentifier = @"chatCell";
ChatCell *cell = (ChatCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];

if (!cell) {
    cell = [[ChatCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
info = [receivedData objectAtIndex:indexPath.row];
message = [info objectForKey:@"message"];
CGSize constraint = CGSizeMake(220, 2000);
CGRect rect = [message boundingRectWithSize:constraint options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12.0f]} context:nil];
CGSize size = rect.size;

使用该信息,我将表格行高度设置为heightForRowAtIndexPath。但调整标签cell.messageLabel的框架没有给我任何结果。这是我在cellForRowAtIndexPath中试过的其他东西:

UIView *messageFrame = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 220, size.height)];
[messageFrame addSubview:cell.messageLabel];
[cell addSubview:messageFrame];

但这是模拟器中的结果:

Image

一切都向上移动,整个文字都没有显示出来。有没有一个简单的解决方案,还是我必须重新考虑我的整个代码?

解答: 我所做的是在故事板中添加一个UIView,并将它的约束放在单元格的底部。由于我是根据ios7中的内容边界函数调整单元格高度,因此将约束设置为底部会自动将UIView拉伸到底部。玩消息标签宽度,我得到填充。希望这有助于某人。

0 个答案:

没有答案