UILabel の高さによって UITableViewCell の高さを変える
はじめに
表題を実現するためのコードをメモします。
sizeWithFontメソッドは iOS7 で非推奨なので boundingRectWithSizeメソッドを使います。
UILabel のカテゴリとして実装しました。
コード
カテゴリで追加したメソッドが衝突しにくように、メソッド名にプリフィックス xx_ をつけました。適宜プロジェクトのそれにおきかえてください。
UILabel+EstimatedHeight.h
@interface UILabel (EstimatedHeight) + (CGFloat)xx_estimatedHeight:(UIFont *)font text:(NSString *)text size:(CGSize)size; @end
UILabel+EstimatedHeight.m
#import "UILabel+EstimatedHeight.m" @implementation UILabel (EstimatedHeight) + (CGFloat)xx_estimatedHeight:(UIFont *)font text:(NSString *)text size:(CGSize)size { NSDictionary *attributes = @{NSFontAttributeName: font}; NSAttributedString *string = [[NSAttributedString alloc] initWithString:text attributes:attributes]; CGRect rect = [string boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin context:nil]; return rect.size.height; }
適用したい ViewController.m
#import "UILabel+EstimatedHeight.h" ... - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath { YourModel *model = self.models[indexPath.row]; CGFloat height = [UILabel xx_estimatedHeight:[UIFont systemFontOfSize:15] text:model.content size:CGSizeMake(280, MAXFLOAT)]; CGFloat margin = 15 * 2; return height + margin; } @end