cell上button点击,确定哪一行cell的三种实现

序言:

我们项目中会遇到自定义cell,然后点击cell中button把值push到下一页面,或者点击该button让cell伸展通过改变cell的高度,这时问题就来了,我怎么知道我点击的是哪一行cell的button,一共有三种实现方式

1.button添加tag

在代理方法给cell的button添加tag

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ATableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"aCell" forIndexPath:indexPath];
    cell.pushButton.tag = indexPath.row;
    cell.delegate = self;
    return cell;
}

点击button,直接取button的tag就ok

    BViewController *b = [self.storyboard instantiateViewControllerWithIdentifier:@"B"];
    b.str = [NSString stringWithFormat:@"俺从第%ld过来的",button.tag];
    [self.navigationController pushViewController:b animated:YES];
}

2.根据point取indexpath

为button添加点击方法

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ATableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"aCell" forIndexPath:indexPath];
    [cell.pushTwoButton addTarget:self action:@selector(pushTwo:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

indexPathForRowAtPoint方法实现

-(void)pushTwo:(UIButton *)sender{
    CGPoint point = sender.center;
    point = [self.tableView convertPoint:point fromView:sender.superview];
    NSIndexPath* indexpath = [self.tableView indexPathForRowAtPoint:point];
     BViewController *b = [self.storyboard instantiateViewControllerWithIdentifier:@"B"];
    b.str =[NSString stringWithFormat:@"俺从第%ld过来的",indexpath.row];
    [self.navigationController pushViewController:b animated:YES];
}

3.让controller成为cell的代理把cell 传到controller

@class ATableViewCell;
@protocol ATableViewCellDelegate<NSObject>
@optional
-(void)pushThree:( ATableViewCell*)cell;
@end
@interface ATableViewCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UIButton *pushButton;
@property (weak, nonatomic) IBOutlet UIButton *pushTwoButton;
@property(nonatomic,weak)id<ATableViewCellDelegate>delegate;
@end

- (IBAction)pushThree:(UIButton *)sender {
    if (self.delegate && [self.delegate respondsToSelector:@selector(pushThree:)]) {
        [self.delegate pushThree:self];
    }
}

再在代理方法中通过indexPathForCell实现

-(void)pushThree:(ATableViewCell *)cell{
     NSIndexPath * indexPath = [self.tableView indexPathForCell:cell];
    BViewController *b = [self.storyboard instantiateViewControllerWithIdentifier:@"B"];
    b.str =[NSString stringWithFormat:@"俺从第%ld过来的",indexPath.row];
    [self.navigationController pushViewController:b animated:YES];
}

demo链接

记录一下,加深印象,如果碰巧能够解决你的问题,欢迎star,谢谢!!!
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容