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

今天在开发过程中碰到这个问题,在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开发不久,还在学习阶段,有什么错误希望大神指教。谢谢了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章