LoginSignup
10
10

More than 5 years have passed since last update.

RZCellSizeManagerを使ってカスタムセルの高さを簡単に扱う

Last updated at Posted at 2014-05-29

セルの高さを可変にした場合、heightForRowAtIndexPath:を書いていくのが大変だったのでライブラリを探してみました。RZCellSizeManagerというセルの高さ計算を専門で取り扱うライブラリを使ってみたのでメモ。

前提

  • iOS 7.0 or later
  • AutoLayout

RZCellSizeManagerのインストール

CocoaPodsから入れます。

Podfile
pod "RZCellSizeManager"

実装

プロパティの追加

ビュークラス / ビューコントローラクラスにRZCellSizeManagerのプロパティを生やします。

@interface SomeViewController

@property (strong, nonatomic) NSArray *objects;  // Cellで使用するデータ
@property (strong, nonatomic) RZCellSizeManager *sizeManager;  // RZCellSizeManagerのインスタンス

@end

初期化と設定

適当なタイミングでRZCellSizeManagerを初期化します。ViewControllerならviewDidLoad, Viewならカスタムイニシャライザで初期化すると良いんじゃないかと思います。

- (void)initCellSizeManager
{
    // RZCellSizeManagerの初期化
    _sizeManager = [[RZCellSizeManager alloc] init];

    // RZCellSizeManagerにカスタムセルの登録
    [_sizeManager registerCellClassName:NSStringFromClass([CustomCell class])
                           withNibNamed:nil
                     forReuseIdentifier:@"CustomCell"
                 withConfigurationBlock:^(CustomCell *cell, SomeObject *object) {
                     // カスタムセルに値をセットしてレイアウト変更する
                     cell.someObject = object;
                 }];
}

セルの取得

tableViewにセルを返すときはいつもどおりでOK。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell"
                                                       forIndexPath:indexPath];
    cell.someObject = [_objects objectAtIndex:(NSUInteger) indexPath.row];

    return cell;
}

セルの高さを取得

RZCellSizeManagerからセルの高さを取得します。

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // セル表示用のオブジェクトを取得
    id object = [_objects objectAtIndex:(NSUInteger) indexPath.row];

    // RZCellSizeManagerから表示用オブジェクトに対応したセルの高さを取得する
    CGFloat height = [_sizeManager cellHeightForObject:object
                                             indexPath:indexPath
                                   cellReuseIdentifier:@"CustomCell"];
    return height;
}

参考

10
10
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
10
10