#import <UIKit/UIKit.h>
@interface TestCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UIButton *btnTest;
@end
#import "ViewController.h"
#import "TestCell.h"
#import <objc/runtime.h>
static void *btnIndexPathKey = "btnIndexPathKey";
@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 5;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
TestCell *test = [tableView dequeueReusableCellWithIdentifier:@"TestCell" forIndexPath:indexPath];
/**设置cell上button的关联对象*/
objc_setAssociatedObject(test.btnTest, btnIndexPathKey, indexPath, OBJC_ASSOCIATION_ASSIGN);
return test;
}
- (IBAction)btnClick:(UIButton *)sender
{
/**获取对应关联对象的值*/
NSIndexPath *btnIndexPath = objc_getAssociatedObject(sender, btnIndexPathKey);
NSLog(@"btnIndexPath.row = %ld",btnIndexPath.row);
}