iOS 自定义UITableViewCell上添加UIButton按钮实现选中的是哪个按钮对应的cell,用代理实现。

自定义UITableViewCell上添加UIButton按钮实现选中的是哪个按钮对应的cell,用代理实现。

1.第一步,再自定义cell的.h文件中,声明一个协议;

#import
//创建一个代理,用于点击按钮的时候将当前cell传到控制器中,
@protocol myTabVdelegate
-(void)myTabVClick:(UITableViewCell *)cell;
@end

@interface CustomTableViewCell : UITableViewCell
//声明一个代理属性
@property(assign,nonatomic)iddelegate;

@property(strong,nonatomic)UIButton *btn;

@end

iOS 自定义UITableViewCell上添加UIButton按钮实现选中的是哪个按钮对应的cell,用代理实现。_第1张图片


2.在自定义cell的.m文件中,添加一个uibutton按钮,并实现点击事件中调用代理方法

//按钮点击触发事件

-(void)testAction:(UIButton *)sender

{

     [self.delegatemyTabVClick:self];

}


iOS 自定义UITableViewCell上添加UIButton按钮实现选中的是哪个按钮对应的cell,用代理实现。_第2张图片


3.在控制器中,添加UITableView ,实现代理,并且实现自定义cell中,所声明的代理。(.h文件导入协议)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

   staticNSString *identify =@"identify";

   CustomTableViewCell *cell = [tableViewdequeueReusableCellWithIdentifier:identify];

   if (!cell) {

        cell = [[CustomTableViewCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:identify];

    }

    //给代理赋值

    cell.delegate =self;

   return cell;

}

//实现代理

-(void)myTabVClick:(UITableViewCell *)cell

{

    NSIndexPath *index = [_tableV indexPathForCell:cell];

    NSLog(@"当前点击是哪个单元格上的按钮===%d",index.row);

    

}



iOS 自定义UITableViewCell上添加UIButton按钮实现选中的是哪个按钮对应的cell,用代理实现。_第3张图片

iOS 自定义UITableViewCell上添加UIButton按钮实现选中的是哪个按钮对应的cell,用代理实现。_第4张图片


4.ok ,运行,搞定。。


demo 地址:点击下载Demo

ps:做一个快乐的程序猿,每天进步一点点。欢迎指导!!!!

你可能感兴趣的:(iOS)