美文网首页边开发边学习
点击cell上的按钮获取所在的行

点击cell上的按钮获取所在的行

作者: coderhlt | 来源:发表于2017-07-10 17:05 被阅读8次

说明:点击cell上的按钮获取所在的行,在开发中我们会经常使用的到,整理下常用的方法,简单的tag就不用说了。

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if(self){
        UIButton *btn=[[UIButton alloc]init];
        [self addSubview:btn];
        btn.frame=CGRectMake(100, 10, 40, 40);
        btn.backgroundColor=[UIColor redColor];
        [self addSubview:btn];
        [btn addTarget:self action:@selector(clcik: event:) forControlEvents:UIControlEventTouchUpInside];
    }
    return  self;
}

# 方法一 :
- (void)clcik:(UIButton*)sender event:(id)event{
    NSSet *touchs=[event allTouches];
    UITouch *touch=[touchs anyObject];
    CGPoint touchposition=[touch locationInView:self.tableview ];
    NSIndexPath *indexpath=[self.tableview indexPathForRowAtPoint:touchposition];
    NSLog(@"%lid",(long)indexpath.row);
}

# 方法二 :
- (void)clcik:(UIButton*)sender event:(id)event{
    Selfcell *cell= (Selfcell *)sender.superview;
    NSIndexPath *indexpath=[self.tableview indexPathForCell:cell];
    NSLog(@"%lid",(long)indexpath.row);
}

相关文章

网友评论

  • lcc小莫:好棒,第一种我知道,第二种没用过。

本文标题:点击cell上的按钮获取所在的行

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