使用NSAttributedString iOS自定义heightForRowAtIndexPath(CGSize sizeWithFont)

HpT*_*erm 4 uitableview ios6 ios7

我有一个表视图,其中我的单元格高度是动态定义的,具体取决于它所代表的文本.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //getting my text for this cell, the row etc ...
    ...
    //here is the part interesting us
    NSAttributedString* theText = [myTextForThisCell objectAtIndex:indexPath.row];

    NSInteger labelWidth = self.tableView.bounds.size.width-HORIZONTAL_CELL_PADDING;

    CGSize textSize = [theText sizeWithFont:[UIFont systemFontOfSize:customFontSize] constrainedToSize:CGSizeMake(labelWidth, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];

    return textSize.height+VERTICAL_CELL_PADDING;
}
Run Code Online (Sandbox Code Playgroud)

好吧,现在我的问题.tableview是搜索操作的结果,扫描plist文件后显示包含给定字符串的行.

到目前为止就是这样.但是现在使用iOS 6和NSAttributedString可以轻松地加粗部分字符串,我决定加粗搜索字.

它正在工作,它大胆地说出我想要的单词,但现在我无法计算单元格高度,因为sizeWithFont要求NSString.并且由于粗体占用更宽的宽度,我不能简单地用没有属性的字符串计算单元格高度.

我只是被困在这里.

有人可以帮帮我吗?

HpT*_*erm 23

事实上,我只需要阅读NSAttributedText的苹果文档.

在我的情况下,我必须替换最后两行代码

CGRect rectSize = [theText boundingRectWithSize:CGSizeMake(labelWidth, MAXFLOAT) 
                         options:NSStringDrawingUsesLineFragmentOrigin context:NULL];

return rectSize.size.height+VERTICAL_CELL_PADDING;
Run Code Online (Sandbox Code Playgroud)

跟随iOS 7

我一直在努力在iOS7中使用属性文本来完成这项工作.

Apple文档说

在iOS 7及更高版本中,此方法返回小数大小(在返回的CGRect的大小组件中); 要使用返回的大小来调整视图大小,必须使用ceil函数将其值提升到最接近的更高整数.

哪种方式显然不适合我!对我来说,解决方案是在高度上添加+1.这可能是Apple的一个错误,但对我来说现在一切都像在iOS6中一样.

CGRect rectSize = [theAttributedText boundingRectWithSize:CGSizeMake(labelWidth, MAXFLOAT) 
                          options:NSStringDrawingUsesLineFragmentOrigin context:NULL];

return ceil(rectSize.size.height) + 1 + VERTICAL_CELL_PADDING;
Run Code Online (Sandbox Code Playgroud)