iOSアプリ開発のメモ置き場

ささたつがiOSアプリ開発で知ったObjective-Cのtipsなどを書いていく所存

テーブルビューのセル毎にピッタリの高さを計算する

高さが固定じゃなく、セルの内容毎に高さが変わる場合がありますよね。

そういう場合には 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;
}

参考:UITableViewCellの高さを動的に変えるサンプル