我最近完成了这个,发现它非常简单。而不是使用sizeWithFont:
你应该使用boundingRectWithSize:options:attributes:context
iOS 7 中的新方法。
像往常一样设置表格视图单元格并preferredFontForTextStyle:
在文本标签上指定如下:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TableViewCellIdentifier forIndexPath:indexPath];
//set your table view cell content here
[[cell textLabel] setText:@"Lorem ipsum dolour sit amet."];
[[cell textLabel] setNumberOfLines:0];
[[cell textLabel] setLineBreakMode:NSLineBreakByWordWrapping];
[[cell textLabel] setFont:[UIFont preferredFontForTextStyle:UIFontTextStyleBody]];
return cell;
}
然后正确确定文本标签的大小,boundingRectWithSize:options:attributes:context
计算所需的高度。
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//add your table view cell content here
NSString *string = @"Lorem ipsum dolor sit amet.";
NSDictionary *attributes = @{NSFontAttributeName: [UIFont preferredFontForTextStyle:UIFontTextStyleBody]};
CGRect frame = [string boundingRectWithSize:CGSizeMake(CGRectGetWidth(tableView.bounds), CGFLOAT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) attributes:attributes context:nil];
return ceilf(CGRectGetHeight(frame);
}
您可能还希望将表格视图单元格子类化以侦听UIContentSizeCategoryDidChangeNotification
通知,此时您可以在用户在 Settings.app 中更改其偏好时更新您的 UI
- (void)contentSizeCategoryDidChangeNotificationHandler:(NSNotification *)notification
{
[[self textLabel] setFont:[UIFont preferredFontForTextStyle:UIFontTextStyleBody]];
}
如果您需要文本标签周围的额外填充,您可以定义一个常量值,例如
static CGFloat const TableViewCellPadding = 10.0;
有了这个,您可以向从返回的值添加一个常量值tableView:heightForRowAtIndexPath:
return (ceilf(CGRectGetHeight(frame) + TableViewCellPadding);
或者您可以这样插入返回的帧boundingRectWithSize:options:attributes:context
:
CGRect frame = [string boundingRectWithSize:CGSizeMake(CGRectGetWidth(tableView.bounds), CGFLOAT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) attributes:attributes context:nil];
frame = CGRectInset(frame, 0.0, TableViewCellPadding);