我试图让我的表格视图单元格根据单元格内的内容调整它们的高度。
由于单元格的高度不同,它似乎可以正常工作,但我无法正确显示文本。
表格视图和原型单元格是使用情节提要创建的,并且我有一个自定义单元格类链接到我的原型单元格。在我的原型单元格中,我有三个标签;标题标签、日期标签和具有动态文本数据的标签。在情节提要的属性检查器中,动态文本数据标签行号设置为 0,换行符设置为“自动换行”。
当我运行应用程序时,单元格高度都不同,所以我假设索引路径处的行高度有效:
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Text data
NSDictionary *cellOutputDict = [newsDataArray objectAtIndex:indexPath.row];
NSString *text = [NSString stringWithFormat:@"%@", [cellOutputDict objectForKey:@"text"]];
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:nil];
CGFloat width = 280;
CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
CGSize size = rect.size;
return size.height + 2 * 20; // size.height plus 2 times the desired margin
}
这是我在索引路径处的行单元格:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"NewsCell";
NewsCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// If the cell doesn't exists create it
if (cell == nil) {
cell = [[NewsCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// Configure the cell...
// Text data
NSDictionary *cellOutputDict = [newsDataArray objectAtIndex:indexPath.row];
cell.titleLabel.text = [NSString stringWithFormat:@"%@", [cellOutputDict objectForKey:@"title"]];
cell.dateLabel.text = [NSString stringWithFormat:@"%@", [cellOutputDict objectForKey:@"date"]];
cell.newsTextLabel.text = [NSString stringWithFormat:@"%@", [cellOutputDict objectForKey:@"text"]];
return cell;
}
打印出动态文本数据的 cell.newsTextLabel.text 显示在单元格中,但只显示第一行。
我已经尝试了一些显示 iOS 6.1 的动态单元格高度的示例,它们工作正常,但我无法让它在 iOS 7+ 上工作
所以我希望有人可以帮助解决这个问题并帮助我弄清楚我做错了什么。