プログラミングノート

一からものを作ることが好きなエンジニアの開発ブログです。

UITableViewCellの利用

UITableViewでカスタムセルをコードで作成する方法です。UITableVIewの利用で作成したコードとの差分のみ掲載しています。完全なサンプルはこちらからどうぞ。


MyTableCell.h

まずはUITableViewCellを継承したMyTableCellを追加します。

#import <UIKit/UIKit.h>
// Identifier
extern NSString *myCellID;

@interface MyTableCell : UITableViewCell {
  UILabel *titleLabel;
}
@property (nonatomic, retain) UILabel *titleLabel;
@end

externで定義しているものが、Cell再利用用のIdentifierになります。
あとはCell内に表示するラベルを追加しています。

MyTableCell.m

Cellの実装部です。

#import "MyTableCell.h"

NSString *myCellID = @"myCellID";

@implementation MyTableCell

@synthesize titleLabel;

- (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
  if (self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) {
    // ラベルの設定
    titleLabel = [[UILabel alloc] initWithFrame:frame];
    titleLabel.font = [UIFont systemFontOfSize:15];    
    titleLabel.frame = CGRectMake(10.0, 0.0, 320.0, 40.0);
    [self.contentView addSubview:titleLabel];
    // アクセサリーの設定
    self.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;    
  }
  return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
  [super setSelected:selected animated:animated];
}

- (void)dealloc {
  [titleLabel release];
  [super dealloc];
}
@end

実装部では初期化時に画面に表示するラベルの設定と、セルの右側に表示されるアクセサリーの設定を行っています。contentViewにUI部品を追加すればセルに表示されます。


アクセサリーはこのほかにUITableViewCellAccessoryCheckmarkとUITableViewCellAccessoryDisclosureIndicatorの指定が可能です。

MyViewController.m

最後にCell生成ロジックの変更をします。

#import "MyTableCell.h"

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {  

  MyTableCell *cell = (MyTableCell *)[myTableView dequeueReusableCellWithIdentifier: myCellID];
  if (cell == nil) {
    cell = [[[MyTableCell alloc] initWithFrame:CGRectZero reuseIdentifier:myCellID] autorelease];  

    //ストライプ用の設定
    UIView *bgView = [[UILabel alloc] initWithFrame:CGRectZero];
    cell.backgroundView = bgView;
    [bgView release];
    
    for(UIView *view in cell.contentView.subviews){
      view.backgroundColor = [UIColor clearColor];
    }  
  }
  
  cell.titleLabel.text = [NSString stringWithFormat:@"%@ %i", @"row", indexPath.row];  
  
  //ストライプ用の設定
  if(indexPath.row % 2){
    cell.backgroundView.backgroundColor = [UIColor whiteColor];
  }else{
    cell.backgroundView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:1.0 alpha:0.1]; 
  }    
  return cell;
}   

この部分はInterface Builderを使ってカスタムセルを作成する場合と変わりません。Identifierで定義されたCellが生成されていない場合のみ生成されます。ストライプの設定はUITableViewで縞模様(ストライプ)を参考にさせて頂きました。