9/12/2011

UITableViewCell内部にあるUIImageViewをタップした時の処理

UIImageViewを含むカスタマイズされたUITableViewCellがあったとする。
このUIImageViewをタップした時に何らかの処理を実行したい時の実装例。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = CELLIDENTIFIER;
    
    MyTableViewCell *cell = (MyTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
UIViewController* viewController = [[UIViewController alloc] initWithNibName:CellIdentifier bundle:nil];
        cell = (MyTableViewCell *)viewController.view;
        [viewController release];
    }
    
    // Configure the cell...
cell.imageURL = @"http://sample.com/sample.png";
cell.iconImageView.userInteractionEnabled = YES;
cell.iconImageView.image = [UIImage imageNamed:@"tapme.png"];
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapImage:)];
tapGesture.numberOfTapsRequired = 1;
[cell.iconImageView addGestureRecognizer:tapGesture];
[tapGesture release],tapGesture = nil;
    return cell;
}

- (void)tapImage:(id)sender{
UIImageView *imgView = (UIImageView *)[sender view];
if ([imgView.image isEqual:noImage]) {
BooksTableViewCell *cell = (BooksTableViewCell *)[[imgView superview]superview];
NSLog(@"%@",[[imgView superview]class]);
NSLog(@"%@",[[[imgView superview]superview]class]);
NSURL *imgURL = [NSURL URLWithString:cell.imageURL];
NSLog(@"%@",cell.imageURL);
UIImage *img = nil;
NSData *data = [NSData dataWithContentsOfURL:imgURL];
if (data) {
img = [UIImage imageWithData:data];
[cell.iconImageView setImage:img];
} else {
return;
}
}
}

上の実装例ではMyTableViewCellに画像URLを持たせて、UIImageViewをタップしたらsample.pngをダウンロードしてtapme.pngと差し替えるといった処理を行っている。
UITableViewは画像を持つセルを多数表示するとメモリ不足で落ちたりするので、このような処理もメモリ使用量を節減する選択肢となり得る。
実際の実装では画像URLは配列から取り出すことになるだろうし、tapme.pngも1つのインスタンスを使い回すことになるだろう。

- (void)tapImage:(id)senderメソッドについては、[sender view]は確かにここでいうタップしたiconImageViewなのだが、iconImageViewとMyTableViewCellの間にUITableViewCellContentViewが挟まっているので、それをNSLogで明示している。

0 件のコメント:

コメントを投稿