[英]IOS Dynamic Tableviewcell, strange UILabel behavior
我有一个动态表格视图,可以从Web上的XML文件加载数据。 原型单元仅是两个标签(堆叠)和位于视图底部的三个按钮。 我添加了代码以根据标签的文本长度扩展第二个标签的大小和单元格高度。 一些单元格显示完整的第二个标签,而大多数仅显示第一行。 有时,在我滚动到各个单元后,这些单元会显示完整的第二个标签(从屏幕到屏幕)。 这是我的cellForRowAtIndexPath代码。
static NSString *CellIdentifier = @"localdiningTableCell";
mhgiLocalDiningCell *diningcell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (diningcell == nil) {
diningcell = [[mhgiLocalDiningCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
mhgiDiningXmlObject *object = [self.xmlParser.allItems objectAtIndex:[indexPath row]];
// Configure the cell...
diningcell.nameLabel.text= [object Name];
NSString *typeText = [object Type];
NSString *addressText = [NSString stringWithFormat:@"%@, %@, %@", [object Street], [object City], [object State]];
NSString *distanceText = [NSString stringWithFormat:@"%@ miles from the hotel", [object Distance]];
NSString *descrText = [NSString stringWithFormat:@"%@\n%@\n%@", typeText, addressText, distanceText];
UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:17.0];
CGSize constraintSize = CGSizeMake(260.0f, MAXFLOAT);
CGSize labelSize = [descrText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
CGRect frame = CGRectMake (diningcell.typeLabel.frame.origin.x, diningcell.typeLabel.frame.origin.y, 260.0f, labelSize.height);
diningcell.typeLabel.frame = frame;
diningcell.typeLabel.lineBreakMode = NSLineBreakByWordWrapping;
diningcell.typeLabel.numberOfLines = 0;
diningcell.typeLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0];
diningcell.typeLabel.text = descrText;
return diningcell;
例,
应该看起来像这样
Label 1
Label 2, with some long
text that takes up more than
one line
但是看起来像这样
Label 1
Label 2, with some long
.
.
注意, ”。” 实际未显示出来,只是表示提供了标签的空间。 文本似乎只是在随机单元格上消失了。
1.如果您有mhgiLocalDiningCell.xib,请使用
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"mhgiLocalDiningCell" owner:self options:nil];
if ([nib count] > 0) {
cell = nib[0];
}
}
2.您是否返回了任何行的正确高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
要么
tableView.rowHeight = 44.0f;
您可能要定义一个属性,而不是使用框架:
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *labelHeight;
接着
float width = self.label.frame.size.width
CGSize constraintSize = CGSizeMake(width, MAXFLOAT);
CGSize labelSize = [descrText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
self.labelHeight.constant = labelSize.height;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.