UITableViewのCellは使い回しされているのでサブビューを加えたりカスタマイズする時は注意が必要って備忘録。
■実装
UITableViewCellCustomized.h
#import <UIKit/UIKit.h> @interface UITableViewCellCustomized : UITableViewCell { UILabel *title; } @property (nonatomic, retain) UILabel *title; @end
UITableViewCellCustomized.m
#import "UITableViewCellCustomized.h" @implementation UITableViewCellCustomized @synthesize title; - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; if (self) {// Initialization code // title title = [[[UILabel alloc] initWithFrame:CGRectMake(20, 5, 280, 20)] autorelease]; [title setFont:[UIFont systemFontOfSize:18]]; [self addSubview:title]; // accessory [self setAccessoryType:UITableViewCellAccessoryDisclosureIndicator]; } return self; } - (void)setSelected:(BOOL)selected animated:(BOOL)animated { [super setSelected:selected animated:animated]; } - (void)dealloc { [title release]; } @end
クライアントコード
// create cell - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // call cell UITableViewCellCustomized *cell = (UITableViewCellCustomized *)[tableView dequeueReusableCellWithIdentifier:@"table_cell"]; if (cell == nil) {// create cell cell = [[[UITableViewCellCustomized alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"table_cell"] autorelease]; } [cell.title setText:@"なんらかの文字列"]; return cell; }
上述のようにUITableViewCellを継承したクラスを用意してセットアップする。以下の例のようにしてはならない。
悪い例
以下のように通常の使い回しされているUITableViewCellに直にaddSubviewする。
// create cell - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // cell UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"table_cell"]; cell = nil; if (cell == nil) { cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"table_cell"] autorelease]; } [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator]; // title UILabel *title = [[[UILabel alloc] initWithFrame:CGRectMake(20, 5, 280, 20)] autorelease]; [title setText:@"なんらかの文字列"]; [cell addSubview:title]; return cell; }