直接在cellForRowAtIndexPath方法中添加一个button,把当前indexPath.row赋值给btn的tag,在button的selector方法中打印button.tag,或者找button的父视图的父视图UITableViewCell,使用方法NSIndexPath * path = [self.tableView indexPathForCell:cell]; 打印当前所在index的row
实现:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath方法中添加一个button{
static NSString * cellID = @"myCell";
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
}
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.backgroundColor = [UIColor orangeColor];
btn.frame = CGRectMake(0, 0, 100,30);
[btn setTitle:[NSString stringWithFormat:@"index.row = %d",indexPath.row] forState:UIControlStateNormal];
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:btn];
btn.tag = indexPath.row; //把当前indexPath.row赋值给btn的tag
return cell;
}在设置的Button的selector的方法中如下设置:
- (void)btnClick:(UIButton *)sender {
//找当前cell上sender的父视图的父视图UITableViewCell,sender的父视图是UITableViewCellContentView
NSIndexPath * path = [self.tableView indexPathForCell:cell];
NSLog(@"index row%d", [path row]);
/*或者直接写
NSLog(@"index row%d", sender.tag);
*/
}