UITableViewCellのいくつかの操作--indexPathの取得

2468 ワード

まず簡単に、cell上でbuttonがイベント応答をクリックすると、buttonがいるcellのindexPathを取得します.
#import "ViewController.h"

@interface ViewController () 
@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];