美文网首页
cell上button点击,确定哪一行cell的三种实现

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

作者: 谁偷走了我爱吃的奶酪 | 来源:发表于2018-05-26 17:20 被阅读0次

序言:

我们项目中会遇到自定义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,谢谢!!!

相关文章

网友评论

      本文标题:cell上button点击,确定哪一行cell的三种实现

      本文链接:https://www.haomeiwen.com/subject/gedmjftx.html