iPhoneアプリでカスタムTableViewCellの作り方

Interface BuilderでカスタムUITableViewCellを作るのにてまどったのでメモ。
xibファイルからViewを作成するときも同じ手順が必要。

手順

【概要】

・UITableViewCell継承クラス(TableViewCellSample)を作成
・Interface BuilderでTableViewCellSampleのxibを作成
・TableViewCellSample、UIViewControllerをInterface Builderで関連付ける
・UITableViewでTableViewCellSampleを生成する

【詳細】

・UITableViewCell継承クラスを作成
UIImageView、UILabelを持つViewを作成


TableViewCellSample.h

@interface TableViewCellSample : UITableViewCell {
    UIImageView* imageView;
    UILabel* label1;
    UILabel* label2;
}

@property (nonatomic, retain) IBOutlet UIImageView* imageView;
@property (nonatomic, retain) IBOutlet UILabel* label1;
@property (nonatomic, retain) IBOutlet UILabel* label2;

@end

TableViewCellSample.mは省略


・Interface BuilderでUITableViewCellのxibを作成

ファイル>新規作成>View XIBを作成で、Viewのxibを作成します。

UIViewを削除し、UITableViewを追加します。

File's OwnerのclassにUIViewControllerを指定します(ここ重要です)。
UITableViewCellのclassにTableViewCellSampleを指定します。

デザインは適当で。。。

TableViewCellSampleのAttributes Inspectorで、セルをキャッシュするときのIdentifierを指定する


・TableViewCellSample、UIViewControllerをInterface Builderで関連付ける

TableViewCellSampleのUIImageView,UILabelの関連づけを行います。

UIViewControllerのviewをTableViewCellSampleに関連づけます。
忘れがちなので注意。


・UITableViewでTableViewCellSampleを生成する

// テーブルレコード数
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {
    return 5;
}

// テーブルセル
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
    static NSString* cellIdentifier0 = @"TableViewCellSample";
	
    // セルがキャッシュされていれば、使い回す。
    TableViewCellSample* cell = (TableViewCellSample*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier0];
    if(cell == nil) {
        // initWithNibNameでTableViewCellSampleを作るためだけのUIViewControllerを生成する
        UIViewController* viewController = [[UIViewController alloc] initWithNibName:cellIdentifier0 bundle:nil];
        // TableViewCellSampleを取り出す
        cell = (TableViewCellSample*)viewController.view;
        // UIViewControllerはいらないので破棄する
        [viewController release];
    }
		
    // set up cell
		
    return cell;
}


注意するところは、xib(nib)ファイルからViewをインスタンス化するには、UIViewControllerのinitWithNibNameを呼び出す必要がある点です。また、Interface BuilderでUIViewControllerのviewを指定しないと取得できないのでお気をつけ下さい。(私はよく忘れます^^;)


UITableViewの詳細については、別の機会に。。。