垂直对齐标签中的文本与设置的行数

时间:2012-06-23 04:02:29

标签: iphone uilabel

我遇到了上述问题的一些问题。我在表视图中有一个标签(X-300,Y-26,width-192和height-42),它们包含不同长度的随机和未知字符串。最大行数应为2.文本应始终位于标签的顶部。

我有一个可行的解决方案(下面),但它看起来很脏 - 必须有一种更简洁的方法来做一些看起来很简单的事情:

UILabel *cellLabel = (UILabel *)[cell viewWithTag:2];

// First set cell lines back to 0 and reset height and width of the label - otherwise it works until you scroll down as cells are reused.
cellLabel.numberOfLines = 0; 
cellLabel.frame = CGRectMake(cellLabel.frame.origin.x, cellLabel.frame.origin.y, 192, 42);

// Set the text and call size to fit
[cellLabel setText:[[products objectAtIndex:indexPath.row] objectForKey:@"title"]];
[cellLabel sizeToFit];

// Set label back to 2 lines.
cellLabel.numberOfLines = 2;

// This 'if' solves a weird the problem when the text is so long the label ends "..." - and the label is slightly higher.
if (cellLabel.frame.size.height > 42) {
    cellLabel.frame = CGRectMake(cellLabel.frame.origin.x, cellLabel.frame.origin.y, 192, 42);
}

1 个答案:

答案 0 :(得分:1)

这是我使用的,UILabel上的一个类别。我正在设置标签的最大高度+尾部截断。这是我在另一个SO帖子上找到的sizeToFitFixedWidth:方法的修改版本。也许你可以使用这样的东西来容纳你的最大行数?

@implementation UILabel (customSizeToFit)

- (void)sizeToFitFixedWidth:(CGFloat)fixedWidth andMaxHeight:(CGFloat)maxHeight;
{
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, fixedWidth, 0);
    self.lineBreakMode = UILineBreakModeWordWrap;
    self.numberOfLines = 0;
    [self sizeToFit];

    if (maxHeight != 0.0f && self.frame.size.height > maxHeight) {
        self.lineBreakMode = UILineBreakModeTailTruncation;
        self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, fixedWidth, maxHeight);
    }    
}

@end