LoginSignup
114
113

More than 5 years have passed since last update.

UITableViewCellの高さを動的に変更する(初心者向け)

Last updated at Posted at 2014-04-26

中・上級者には当たり前なことばかりだと思うけど、けっこう苦労して調べたのでまとめておきたい。

環境

Xcode5でiOS7をターゲットという前提で。
UIはStoryBoardでつくります。

1. UILabelの設定

UITableViewCellの中に、UIImageViewとUILabelをsubviewとして持つという単純な構造。

  • Lines(numberOfLines)を0にする。
  • Line Breaks(lineBreakMode)を"Character Wrap"にする。

これでテキストが複数行に渡る長さでも改行して表示してくれる。

2. (CGFloat)tableView:heightForRowAtIndexPath:

読んで字のごとく、各行の高さを決めるメソッド。
tableView:cellForRowAtIndexPath: よりも先に呼び出される。

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 表示したい文字列
    NSString     *text = _objects[indexPath.row];
    // 表示最大幅・高さ
    CGSize     maxSize = CGSizeMake(200, CGFLOAT_MAX);
    // 表示するフォントサイズ
    NSDictionary *attr = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:17.0]};

    // 以上踏まえた上で、表示に必要なサイズ
    CGSize modifiedSize = [text boundingRectWithSize:maxSize
                                             options:NSStringDrawingUsesLineFragmentOrigin
                                          attributes:attr
                                             context:nil
                           ].size;

    // 上下10pxずつの余白を加えたものと70pxのうち、大きい方を返す
    return MAX(modifiedSize.height + 20, 70);
}

3. (UITableViewCell*)tableView:cellForRowAtIndexPath:

おなじみのメソッド。
sizeToFitメソッドを呼び出して、表示する文字列にあわせてUILabelのサイズを伸縮する。

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

    UILabel *label = (UILabel*)[cell viewWithTag:UITableViewCellLabelTag];
    label.text = _objects[indexPath.row];

    // 表示する文字列にフィットするように伸縮
    [label sizeToFit];

    return cell;

完成図

文章がアレですが、世界の諺を引用しているだけであまり深い意味はないです。

114
113
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
114
113