2012-06-23 52 views
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); 
} 
+0

這與xcode無關,而是關於UILabel,所以我刪除了Xcode標記並添加了UILabel標記。 –

回答

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