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