【发布时间】:2014-03-20 02:14:19
【问题描述】:
我查看了较早的问题并尝试了所有建议,但似乎仍然无法让多行 UILabel 工作。我有一个 UITableView 并且单元格是由tableView:cellForRowAtIndexPath:创建的@
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *fieldValue = [self fieldValueAtIndexPath:indexPath];
NSString *fieldName = [self fieldNameAtIndexPath:indexPath];
NSString *title = [[self appDelegate] displayNameForFieldName:fieldName];
Field fieldCode = [[self appDelegate] fieldCodeForFieldName:fieldName];
DetailCell *cell = nil;
NSString *identifier = nil;
BOOL isNotes = [fieldName caseInsensitiveCompare:@"Notes"] == NSOrderedSame;
switch( isNotes ) {
case NO:
{
identifier = @"DetailCell";
cell = (DetailCell*)[tableView dequeueReusableCellWithIdentifier:identifier];
NSInteger rows = [self heightForText:fieldValue andFont:[self textFont] andWidth:cell.value.frame.size.width] / _oneRowSize.height;
cell.value.text = fieldValue;
cell.name.text = [title lowercaseString];
cell.name.numberOfLines = MAX( 1, rows );
cell.value.numberOfLines = cell.name.numberOfLines;
break;
}
case YES:
{
cell = (DetailCell *)[tableView dequeueReusableCellWithIdentifier:@"DetailCellNotes" forIndexPath:indexPath];
// cell = (DetailCell *)[tableView dequeueReusableCellWithIdentifier:@"DetailCellNotes"];
cell.value.text = @"This is a very long line of text which should take up several lines";
cell.name.text = [title lowercaseString];
cell.value.numberOfLines = 5; // No more than 5 lines of text
cell.value.backgroundColor = [UIColor purpleColor];
cell.value.lineBreakMode = NSLineBreakByWordWrapping;
cell.value.frame = CGRectMake(cell.value.frame.origin.x, cell.value.frame.origin.y, 180, 70);
[cell.value sizeThatFits:CGSizeMake(180., 70.)];
break;
}
}
cell.fieldName = fieldName;
return cell;
}
表格视图中的高度是这样定义的
- (CGFloat) tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
NSString *fieldName = [self fieldNameAtIndexPath:indexPath];
CGFloat height = 0.0;
if([fieldName isEqualToString:@"Notes"])
{
height = 70.;
}
else if([fieldName isEqualToString:@"Image"])
{
height = 100.;
};
return height;
}
这使得单元格足够大以容纳 3 行标签。但是,当单元格出现时,标签只有一行(背景为紫色)。
tableview 使用原型单元格,我也尝试将其设置为 numberOfLines=5 和 WordWrapping,但这也没有改变效果。我还尝试了两条注释掉的行(尽管搜索表明 sizeToFit 实际上可能会将 numberOfLines 重置为 1)。
我想知道我错过了什么。我看不到它可能被覆盖的任何其他地方。
谢谢。
【问题讨论】:
-
您是说标签很高但只包含一行文字,还是标签高度错误,即物理高度只有一行?
-
我认为标签尺寸不对。我放了紫色背景来证明给自己看。标签只有一行(紫色),单元格的其余部分为白色。不幸的是,在我获得更高的声誉之前,我不能在这里发布图片。
-
您能否显示您的
tableView:cellForRowAtIndexPath:实现的全文?我确信这就是问题所在。 -
好像你的标签框不够高。要根据单元格的高度使标签的高度跟随/添加,您需要使用约束或使用 AutoResizingMask(可以直接在 XIB/Storyboard 中完成),无论哪种方式都可以告诉标签如何调整大小超级视图调整大小。使用约束的另一个替代解决方案是在您的
tableView:cellForRowAtIndexPath:实现的代码中显式调用cell.value上的sizeToFit:,以便在您设置其文本后强制它调整其框架。 -
matt - 我更新了代码以反映完全正常的
tableview:cellForRowAtIndexPath。它仍然显示问题。你会看到我也试过dequeueReusableCellWithIdentifier:forIndexPath
标签: ios uitableview uilabel