哪个是Autolayout中最好的方法,或者使用NSAttributedString计算高度,以实现UITableViewCell的动态高度?

时间:2015-04-10 13:57:42

标签: ios objective-c uitableview autolayout nsattributedstring

我已经按照http://raywenderlich.com/73602/dynamic-table-view-cell-height-auto-layout中的教程进行了实现并实现了相同的功能,但是随着iOS 8.3的发布,上面的教程似乎并没有起作用。

因此我切换回以下代码,该代码完全正常

-(float)height :(NSMutableAttributedString*)string
{
  NSAttributedString *attributedText = string;

  CGRect rect = [attributedText boundingRectWithSize:CGSizeMake(200, MAXFLOAT)
                                           options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                           context:nil];
  CGSize requiredSize = rect.size;
  return requiredSize.height;
}

并在

中调用相同内容
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{   
  CGFloat heightOfcell = [self height:[array objectAtIndex:indexPath.row]];
  return heightOfcell;
}

有人可以建议一种更好的方法在自动布局中做同样的事情而我不使用StoryBoard吗?

1 个答案:

答案 0 :(得分:1)

我建议在单元格的内容视图中使用Autolatyout,并在viewDidLoad中给出一个估计的行高,例如self.tableView.estimatedRowHeight = 200;但是这个apporach可能不支持早期版本的IOS。