首先比较简单,先获当cell上button点击事件响应,获取button所在cell 的indexPath
#import "ViewController.h"
@interface ViewController () <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, assign) NSInteger num;
@property (nonatomic, strong) UITableView * tableView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:(UITableViewStylePlain)];
self.tableView.backgroundColor = [UIColor whiteColor];
self.tableView.delegate = self;
self.tableView.dataSource = self;
[self.view addSubview:self.tableView];
// Do any additional setup after loading the view, typically from a nib.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"cell"];
if (self.num < 10) {
cell.textLabel.text = [NSString stringWithFormat:@"%ld",self.num];
self.num ++;
}
UIButton * btn = [UIButton buttonWithType:(UIButtonTypeSystem)];
btn.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 120 , 10, 100, cell.contentView.frame.size.height - 20);
btn.backgroundColor = [UIColor whiteColor];
[btn setTitle:@"点击" forState:(UIControlStateNormal)];
[btn addTarget:self action:@selector(buttonDidClick:) forControlEvents:(UIControlEventTouchUpInside)];
[cell.contentView addSubview:btn];
}
return cell;
}
- (void)buttonDidClick:(UIButton *) sender {
UITableViewCell * cell = (UITableViewCell *)[[sender superview] superview];
NSIndexPath * index = [self.tableView indexPathForCell:cell];
NSLog(@" 当前点击的是第 %ld 行",index.row);
}
已知indexPath,获取对应的Cell
NSIndexPath * cellIndex = [NSIndexPath indexPathForRow:3 inSection:0];
UITableViewCell * cell = [self.tableView cellForRowAtIndexPath:cellIndex];