LoginSignup
51
50

More than 5 years have passed since last update.

Objective-C:UITableViewCell上に配置したButtonのタップを感知する方法

Posted at

やり方
カスタムセルを生成する際にaddTarget:actionでイベントを設定しておく。
UIEventからタッチした座標を取得して、その座標からどのセル(indexPath)なのかを取得できる(indexPathForControlEventメソッド部分)ので、それぞれのセルに合わせたボタン動作等を定義できる。

#pragma mark - UITableViewData
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // CustomCellViewは別途定義してあるものとする
    CustomCellView *cell = [tableView dequeueReusableCellWithIdentifier:@"customCellView"];
    if (!cell) {
        cell = [[CustomCellView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"customCellView"];
    }
    // イベントを付ける
    [cell.EventButton addTarget:self action:@selector(handleTouchButton:event:) forControlEvents:UIControlEventTouchUpInside];

    return cell;
}

#pragma mark - handleTouchEvent
- (void)handleTouchButton:(UIButton *)sender event:(UIEvent *)event {
    NSIndexPath *indexPath = [self indexPathForControlEvent:event];
    NSString *messageString = [NSString stringWithFormat:@"Button at section %d row %d was tapped.", indexPath.section, indexPath.row];
    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:@"Button tapped!" message:messageString delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}

// UIControlEventからタッチ位置のindexPathを取得する
- (NSIndexPath *)indexPathForControlEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint p = [touch locationInView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:p];
    return indexPath;
}

参考
Technology-Gym

51
50
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
51
50