iOS UITableView获取cell的indexPath及cell内部按钮点击事件处理

一个页面如果用UITableView来展现数据并进行相关操作,可能会经常遇到cell内部按钮点击事件,点击不同的按钮进行不同的操作或者是展现不同的数据。如下图所示,点击右侧按钮可以拨打每个客户的电话。

点击右侧电话按钮拨打客户电话

由于UITableView的数据是通过其数据源方法来进行展示的,数据通常存储在模型数组中,要想实现cell内部按钮点击获取到对应cell的信息则可以先获得当前cell的indexPath或者通过按钮的TAG值实现。


先来说说前面一种方法,获取当前cell的indexPath。

不过在此之前,首先要确定你的cell创建方式,是Xib自定义创建的cell还是通过纯代码创建的,因为会有一点区别,如果不提前确定创建cell的方式,也会出现错误。

第一种情况:通过XIb创建的cell

Xib创建的cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

static NSString *cellID = @"test";

testCell *cell = (testCell *)[tableView dequeueReusableCellWithIdentifier:cellID];

if (!cell) {
    cell = [[[NSBundle mainBundle]loadNibNamed:@"testCell" owner:self options:nil]lastObject];
}

cell.testLabel.text = self.data[indexPath.row];
//添加按钮点击事件
[cell.testBtn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];

return cell;
}

//按钮点击事件
-(void)click:(UIButton *)btn{

UIView *contentView = [btn superview];
testCell *cell = (testCell *)[contentView superview];
NSIndexPath *indexPath = [self.tb indexPathForCell:cell];

NSLog(@"%@----%@",indexPath,self.data[indexPath.row]);
}

运行结果

从上往下依次点击每一行的按钮,打印结果如下

2017-03-31 16:07:37.077 cell按钮点击事件 代理方法[40818:1294020] <NSIndexPath: 0xc000000000000016> {length = 2, path = 0 - 0}----第一行
2017-03-31 16:07:38.230 cell按钮点击事件 代理方法[40818:1294020] <NSIndexPath: 0xc000000000200016> {length = 2, path = 0 - 1}----第二行
2017-03-31 16:07:39.190 cell按钮点击事件 代理方法[40818:1294020] <NSIndexPath: 0xc000000000400016> {length = 2, path = 0 - 2}----第三行
2017-03-31 16:07:39.919 cell按钮点击事件 代理方法[40818:1294020] <NSIndexPath: 0xc000000000600016> {length = 2, path = 0 - 3}----第四行

第二种情况:纯代码创建的cell

自定义cell的.m文件
#import "customCell.h"

@interface customCell()

@property (nonatomic,strong) UILabel *label;

@end


@implementation customCell


-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{

if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(180, 20, 80, 50)];
    self.label = label;
    
    [self.contentView addSubview:label];
}

return self;

}

-(void)reloadData:(NSArray *)data index:(NSIndexPath *)index{

self.label.text = data[index.row];

}

在ViewController.m里

 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{


static NSString *cellID = @"custom";

customCell *cell = (customCell *)[tableView dequeueReusableCellWithIdentifier:cellID];

if (!cell) {
    cell = [[customCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
}

UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(20, 20, 100, 50)];

[btn setTitle:@"点击一哈" forState:UIControlStateNormal];
[btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
//添加按钮点击事件
[btn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];

[cell addSubview:btn];

[cell reloadData:self.data index:indexPath];

return cell;
}

**使用纯代码创建cell,如果按照前面xib创建cell一样的方法,在按钮的点击事件里代码如下,运行打印结果则并不是正确的。

-(void)click:(UIButton *)btn{

UIView *contentView = (UIView *)[btn superview];

customCell *cell = (customCell *)[contentView superview];

NSIndexPath *path = [self.TB indexPathForCell:cell];

NSLog(@"%@----%@",indexPath,self.data[indexPath.row]);

}
运行效果

从上往下一次点击按钮,打印结果如下:

2017-03-31 16:21:03.668 customCell[41363:1315437] (null)----第一行
2017-03-31 16:21:05.735 customCell[41363:1315437] (null)----第一行
2017-03-31 16:21:06.535 customCell[41363:1315437] (null)----第一行
2017-03-31 16:21:07.407 customCell[41363:1315437] (null)----第一行

**事实上,通过这种子视图获取父视图,然后再调取- (nullable NSIndexPath )indexPathForCell:(UITableViewCell )cell方法获得对应cell的NSIndexPath,两种不同方法创建cell实则存在差异。使用纯代码创建cell的正确方法应该如下

-(void)click:(UIButton *)btn{

customCell *cell  = (customCell *)[btn superview];

NSIndexPath *indexPath = [self.TB indexPathForCell:cell];

}

在使用xib创建自定义cell的时候,倘若通过这种方法获取当前cell的NSIndexPath,可以打开cell的xib视层图,从按钮所在的那个图层依次向上看,遇到一个父视图就调用superview方法,但是别忘了cell的Content View,再用Content View调用一次superview方法才是你展示在tableview中的cell视图。

xib创建cell调用superview

再来后面的一种方法,通过按钮的Tag值来相应对应按钮的点击事件。

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

static NSString *cellID = @"test";

testCell *cell = (testCell *)[tableView dequeueReusableCellWithIdentifier:cellID];

if (!cell) {
    cell = [[[NSBundle mainBundle]loadNibNamed:@"testCell" owner:self options:nil]lastObject];
}

cell.testLabel.text = self.data[indexPath.row];

[cell.testBtn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];

//通常为了避免跟系统tag值冲突,一般都会加上一个大数值,调用的时候再减去这个数值
cell.testBtn.tag = indexPath.row + 9999;


return cell;
}

-(void)click:(UIButton *)btn{

NSLog(@"%ld---%@",btn.tag - 9999 ,self.data[btn.tag - 9999]);

}

从上往下一次点击按钮,打印结果如下:

2017-03-31 16:45:52.941 cell按钮点击事件 代理方法[41664:1326741] 0---第一行
2017-03-31 16:45:53.573 cell按钮点击事件 代理方法[41664:1326741] 1---第二行
2017-03-31 16:45:54.556 cell按钮点击事件 代理方法[41664:1326741] 2---第三行
2017-03-31 16:45:55.212 cell按钮点击事件 代理方法[41664:1326741] 3---第四行

实际上,使用按钮的TAG值是比较简单的方法,但是项目中有大量tag值的,并不推荐使用这个方法,容易造成混乱,不好维护。而且通过tag值获取控件的方式是通过遍历所有子控件的tag值来完成的,效率会比较低下。

tag有什么坏处呢?目前表现出来的坏处就是,使用太多容易混乱,在复杂度较高的程序中,可读性很差。间接的也体现了一些工程师,不爱使用enum枚举的一个陋习,满篇的xxx.tag = 1....之类的代码。

tag有什么好处呢?既然UIKit的class里面都有一个tag属性,肯定是有它存在的道理,tag顾名思义就是给视图打上标签,可以用来遍历子视图,而不用定义property或是nsarray来进行特定的定义或保存指针。举个例子,要你生成10个label,是使用循环生成方便还是通过property一个一个定义方便?当然使用循环+局部变量方便的多,如果这10个label同时存在交互,你就有三个选择:使用tag,或者使用nsarray进行保存指针,或者使用category或继承来自定义控件实现。这里就很明显了,使用tag需要的代码最少,当然也就成了众多工程师们偷懒的一种方式。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 2017.02.22 可以练习,每当这个时候,脑袋就犯困,我这脑袋真是神奇呀,一说让你做事情,你就犯困,你可不要太...
    Carden阅读 1,476评论 0 1
  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,512评论 30 472
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,484评论 4 61
  • 子代选择器 div>p 子代选择器 选择的是p标签 而且父级是div的 p 标签 兄弟选择器 div + p 紧跟...
    小飞侠zzr阅读 646评论 0 0
  • 1. 原来24岁已经是不能熬夜的年纪了。 每次图便宜搭红眼航班之后的一到两天,因为作息被打乱,所以整个人都会呈现一...
    上上上上上好佳阅读 2,036评论 20 16

友情链接更多精彩内容