UITableViewCellを継承せずにカスタムセルを作る方法
テーブルに表示されるデータのレイアウトを少しかえたい時や項目を追加したい時なんかに便利です。
UITableViewControllerを継承したクラスまたはUITableViewDataSourceとUITableViewDelegateプロトコルを実装したクラスのtableView:cellForRowAtIndexPath:メソッドで以下のようにすればOKです。
#define LABEL_TAG 1 #define VALUE_TAG 2 #define CELL_ID @"Cell" - (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath { UILabel *label, *value; UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:CELL_ID]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CELL_ID] autorelease]; cell.selectionStyle = UITableViewCellSelectionStyleNone; label = [[[UILabel alloc] initWithFrame:CGRectMake(0, 12, 70, 25)] autorelease]; label.tag = LABEL_TAG; label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight; [cell.contentView addSubview:label]; value = [[[UILabel alloc] initWithFrame:CGRectMake(75, 12, 200, 25)] autorelease]; value.tag = VALUE_TAG; value.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; [cell.contentView addSubview:value]; } else { label = (UILabel *)[cell.contentView viewWithTag:LABEL_TAG]; value = (UILabel *)[cell.contentView viewWithTag:VALUE_TAG]; } label.text = @"Hoge"; value.text = @"Fuga"; return cell; }
この方法だとコードが少し煩雑になるので項目が増えて複雑になるようであればUITableViewCellのサブクラスを作成したほうがいいと思います。