点击tableViewCell中的一个按钮,打印cell所在的行

直接在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

    UITableViewCell * cell = (UITableViewCell *)[[sender superview] superview];
    NSIndexPath * path = [self.tableView indexPathForCell:cell];

    NSLog(@"index row%d", [path row]);

   /*或者直接写

    NSLog(@"index row%d", sender.tag);

  */

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值