iPhone
カスタムセルを使ってテーブルを表示しているとき、セルの選択によってではなく、カスタムセル内のボタンの選択によって画面遷移を行いたい場合があると思います。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
これではなく・・・
- (void)transitionBySelectedButton:(id)sender
といった自前のメソッドで画面遷移したい。
この場合、それぞれのセルごとにボタンのタッチイベントを定義するには UIEvent を使います。
これでタッチした画面の座標を取得し、どのセルの中にあるボタンかを知ることができます。
UIEvent
タッチやジェスチャーをイベントに関連付けてくれます。
すべてのタッチの座標はUITouchが持っています。
コードは以下。
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *cellIdentifier = kCellIdentifier;
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell){
cell = [[CustomCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
// ボタンのタッチイベント
[cell.button addTarget: self
action: @selector( selectButtonInCell: event: )
forControlEvents: UIControlEventTouchUpInside];
return cell;
}
//
-(void)selectButtonInCell: (UIButton *)sender event: (UIEvent *)event
{
NSIndexPath *indexPath = [self getIndexPathForSelectedButton: event];
NSString *message = [NSString stringWithFormat:
@"Section is %d, Row is %d .",
indexPath.section, indexPath.row];
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"You Tapped This IndexPath!!!!"
message:messageString
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
// UIControlEventからタッチ位置のindexPathを取得する
- (NSIndexPath *)getIndexPathForSelectedButton: (UIEvent *)event
{
UITouch *touch = [[event allTouches] anyObject];
CGPoint p = [touch locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:p];
return indexPath;
}
- 各ボタンのtagの値に見て、処理を行うと、もっと楽ですかも! — 鄒 東金 {2013-02-15 (金) 13:46:02}