本文利用代理实现:
1.先在自定义cell里面创建一个代理
2.自定义cell里面button的点击方法里面实现代理
3.在需要用到的controller里面 签订协议,利用cell
4. 实现代理方法在代理方法里面就能获取到你当前点击的哪一个button,然后通过index获取数据
代码如下:
自定义cell的 .h
#import <UIKit/UIKit.h>
//创建一个代理
@protocol myTabVdelegate <NSObject>
-(void)myTabVClick:(UITableViewCell *)cell nsinterger:(NSInteger )tag;//如果只有一个按钮后面的tag不需要带上
@end
@interface myTableViewCell : UITableViewCell
//声明一个代码块
@property(strong,nonatomic)void(^btnClick)();
@property(strong,nonatomic)UIButton *btn;
@property(strong,nonatomic)UIButton *btn1;
@property(assign,nonatomic)id<myTabVdelegate>delegate;
@end
自定义cell .m
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
//创建两个button按钮
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
_btn = [UIButton buttonWithType:UIButtonTypeCustom];
_btn.frame = CGRectMake(10, 10, 100, 30);
[_btn setTitle:@"test" forState:UIControlStateNormal];
[_btn setBackgroundColor:[UIColor redColor]];
[_btn addTarget:self action:@selector(test:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:_btn];
_btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
_btn1.frame = CGRectMake(100, 10, 100, 30);
[_btn1 setTitle:@"test" forState:UIControlStateNormal];
[_btn1 setBackgroundColor:[UIColor redColor]];
[_btn1 addTarget:self action:@selector(test1:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:_btn1];
}
return self;
}
//按钮事件
-(void)test:(UIButton *)sender
{
[self.delegate myTabVClick:self nsinterger:0];//nsinteger用来区别点击的是同一个cell上面的那个button(比如既有点赞又有评论和收藏的清理)
}
-(void)test1:(UIButton *)sender
{
[self.delegate myTabVClick:self nsinterger:1];//同上
}
//Viewcontroller里面签代理
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identify = @"identify";
myTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
if (!cell) {
cell = [[myTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identify];
}
//给代理赋值
cell.delegate = self;
return cell;
}
//实现代理
- (void)myTabVClick:(UITableViewCell *)cell nsinterger:(NSInteger)tag
{
NSIndexPath *index = [_tableV indexPathForCell:cell];
if (tag == 0) {
NSLog(@"333===%ld",index.row);
}else
{
NSLog(@"4444===%ld",index.row);
}
}