对UITableViewCell的一些操作 -- 获取indexPath

首先比较简单,先获当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];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 2017.02.22 可以练习,每当这个时候,脑袋就犯困,我这脑袋真是神奇呀,一说让你做事情,你就犯困,你可不要太...
    Carden阅读 1,405评论 0 1
  • 好奇触摸事件是如何从屏幕转移到APP内的?困惑于Cell怎么突然不能点击了?纠结于如何实现这个奇葩响应需求?亦或是...
    Lotheve阅读 58,568评论 51 604
  • 在iOS开发中经常会涉及到触摸事件。本想自己总结一下,但是遇到了这篇文章,感觉总结的已经很到位,特此转载。作者:L...
    WQ_UESTC阅读 6,178评论 4 26
  • 1.nav1.navigationBar.barStyle=UIBarStyleBlack; //改变导航栏背景颜...
    SadMine阅读 1,692评论 1 4
  • 1.badgeVaule气泡提示 2.git终端命令方法> pwd查看全部 >cd>ls >之后桌面找到文件夹内容...
    i得深刻方得S阅读 4,815评论 1 9