セルの高さを可変にした場合、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;
}
参考