怎么不使用didselected方法获取选中的cell的行号,区号,indexPath

本文介绍如何在Objective-C中不依赖`didSelectRowAtIndexPath`方法来获取UITableView被选中的cell的行号、区号和indexPath。通过代码片段展示了利用UIButton事件追踪indexPath的技巧。
摘要由CSDN通过智能技术生成
今天在开发过程中碰到这个问题,在cell中定义了button,但是点击cell上的button并不会触发didSelectRowAtIndexPath:这个方法

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

所以可以采用曲线救国的方法  将所有的button全部响应同一个方法,然后在方法中判断是哪一行。

代码片段如下,先创建一个cell

- (UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    //创建cell
    static NSString *identify = @"identify";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identify];
    }
    
    //给cell赋值
    UIButton *btn = [[UIButton alloc] initWithFrame: CGRectMake(0, 0, 64, 44)];
    [cell.contentView addSubview:btn];
    [btn addTarget:self action:@selector(BtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    
    //返回cell
    return cell;
}

然后写出相应的相应方法,一定要确定superView几次后能得到自己的cell。因为我的是在cell中只定义了一个button

所以方向是self(btn) -> contentView -> cell。即需要两次superView。

- (void) rightBtnDidClick:(UIButton *)sender{
    //一定要确定上superView几次后得到的是cell
    UITableViewCell *cell = (UITableViewCell *)[[sender superview] superview];
    NSIndexPath *indexpath = [self.tableView indexPathForCell:cell];
    NSLog(@"%ld",indexpath.row);
}
刚接触ios开发不久,还在学习阶段,有什么错误希望大神指教。谢谢了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值