点击cell上的按钮获取所在的行
2017-07-10 本文已影响8人
coderhlt
说明:点击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);
}