テーブルの各セルにボタンを設置し何行目がタッチされたかを調べる方法
テーブルのセルをカスタマイズしてボタンを設置したときに
何番目のセルのボタンが押されたときはこの処理という風に
処理を分けたいときの方法を調べてみました。
こんな感じで書けば行番号を取得できるようです。
-(void)buttonYpush:(id)sender{
NSLog(@"buttonYpush");
//ボタンでindexPathRowを取得
UIButton *btn = (UIButton *)sender;
UITableViewCell *cell = (UITableViewCell *)[btn superview];
int row = [self.tableView indexPathForCell:cell].row;
NSLog(@"indexpath?:%d",row);
}
他にセルを作成するときに「tag」にindexPath.rowを指定して
行番号を入れる方法があります。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *identifier = @"identifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[UITableView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
[cell autorelelase];
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 5, 40, 20)];
[button addTarget:self action:@selector(buttonPressedAction:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:button];
[button release];
}
UIButton *button = (UIButton *)[cell.contentView.subviews objectAtIndex:0];
[button setTag:indexPath.row];
[button setTitle:@"Edit" forState:UIControlStateNormal];
return cell;
}
- (void)buttonPressedAction:(id)sender
{
UIButton *button = (UIButton *)sender;
int row = button.tag;
}
わたしは「tag」を使う方法でうまくできました。
ボタンの方はやり方をよくわかりませんでした。
参考サイト
UITableViewに設置したUIButtonからindexpath.rowを得る
Detecting which UIButton was pressed in a UITableView
TableViewの各セル内にボタンを配置し、どのボタンがタップされたかを判別可能にする
indexPathForCell: - Cocoa APIとか(iPhoneとか)
iPhoneプログラミング: Table Viewを使ってデータを表示する