2013年1月13日日曜日

Custome UITableViewCellの[self addSubview]と[self.contentView addView]の違い

UITableViewCellを継承してカスタムセルを作成する場合に
self.contentViewに対してaddSubviewするのと
selfにaddSubviewするのとではぱっと見同じでどこが違うんだろうというところが気になったので調べてみた。

わかりやすく背景に色をつけてやってみた。
赤背景 : contentView
青背景 : subviewに追加するview

self版

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.comment = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 200, 30)];
        [self.comment setBackgroundColor:[UIColor blueColor]];
        [self addSubview:self.comment];
        [self setBackgroundColor:[UIColor blueColor]];
        [self.contentView setBackgroundColor:[UIColor redColor]];
    }
    return self;
}

self.contentView版


- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.comment = [[UILabel allocinitWithFrame:CGRectMake(101020030)];
        [self.comment setBackgroundColor:[UIColor blueColor]];
        [self.contentView addSubview:self.comment];
        [self setBackgroundColor:[UIColor blueColor]];
        [self.contentView setBackgroundColor:[UIColor redColor]];
    }
    return self;
}


普通にaddSubviewするだけだと同じ。

http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/TableView_iPhone/TableViewCells/TableViewCells.html#//apple_ref/doc/uid/TP40007451-CH7-SW1

ドキュメント見るとcontentViewの領域は編集とかアクセサリーViewと被らないようにするためっぽい。

■アクセサリーViewを有効にしてみる


- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self setAccessoryType:UITableViewCellAccessoryCheckmark];
        
        self.comment = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 200, 30)];
        [self.comment setBackgroundColor:[UIColor blueColor]];
        [self addSubview:self.comment];
        [self setBackgroundColor:[UIColor blueColor]];
        [self.contentView setBackgroundColor:[UIColor redColor]];
    }
    return self;
}


contentViewの領域が変わった

■編集モードにしてみる( [tableview setEditing:YES] )

self版


self.contentView版


■TableViewのスタイルをグループにする( UITableViewStyleGrouped )

self版




self.contentView版


結論とするとTableViewのスタイルをグループにしたり、編集とかaccessoryViewを使う場合に綺麗に表示するにはcontentViewにaddSubviewしたほうがいいです。
というかドキュメント通りに基本contentViewにaddSubviewすべきです。