0

我对上述问题有一些问题。我在表格视图中有一个标签(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);
}
4

1 回答 1

1

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

@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
于 2012-06-23T04:20:53.560 回答