カスタムセルを使う方法(xibファイル)
カスタムセルを使う方法で色々ハマってしまったのでメモ。
xibファイルを使わずにUITabaleViewCellを継承したクラスを作成した場合は
UITableViewDataSourceのcellForRowAtIndexPathで下記のように記述
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CustomCellIdentifier = @"CustomCellIdentifier"; //CustomTableViewCellはUITabaleViewCellのサブクラス CustomTableViewCell *customCell = (CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier]; if (customCell == nil) { customCell = [[[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CustomCellIdentifier] autorelease]; } [self configureCell:customCell atIndexPath:indexPath]; return customCell; }
xibファイルで定義した場合(xibファイルに付随するクラスを作成した場合も含む)は
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CustomCellIdentifier = @"CustomCell"; CustomTableViewCell *customCell = (CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier]; if (customCell == nil) { //xibファイルから読み込む [[NSBundle mainBundle] loadNibNamed:@"CustomTableViewCell" owner:self options:nil]; customCell = customTableViewCell; self.customTableViewCell = nil; } [self configureCell:customCell atIndexPath:indexPath]; return cell;
xibファイルで生成した際はTableViewCellの[Custom Class]欄にUITableViewCellを継承して作成したクラスを指定する。
File's Ownerの[Custom Class]は、xibで定義したセルをインスタンスとして実際に使用するクラス名を指定する。