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

Iphone 将标签中的文本与设置的行数垂直对齐,iphone,uilabel,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 h

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

这是我使用的,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

这与xcode无关,而是关于UILabel,因此我将删除xcode标记并添加UILabel标记。