テーブルビューのセル毎にピッタリの高さを計算する
高さが固定じゃなく、セルの内容毎に高さが変わる場合がありますよね。
そういう場合には Auto Layout で上下の Constraints を指定しつつ、systemLayoutSizeFittingSize: メソッドを使うと簡単に高さが取得出来ました(ちょっと処理が重い?)。
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { static CustomTableViewCell *sizingCell; static dispatch_once_t predicate; dispatch_once(&predicate, ^{ UINib *nib = [UINib nibWithNibName:@"CustomCell" bundle:nil]; sizingCell = [[nib instantiateWithOwner:nil options:nil] firstObject]; }); sizingCell.bounds = CGRectMake(0.0, 0.0, CGRectGetWidth(tableView.bounds), CGRectGetHeight(sizingCell.bounds)); sizingCell.stock = self.stocks[indexPath.row]; [sizingCell setNeedsLayout]; [sizingCell layoutIfNeeded]; CGSize size = [sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]; return size.height; }