TableView的cell上面加button,实现点击button可以获取到cell的行号或者indexPath

来源:互联网 发布:win7安装数据库2000 编辑:程序博客网 时间:2024/04/29 17:12

在很多时候,我们会用到在TableView的cell上面加button,然后在button触发响应时需要获取所点击的button所在的cell的行标,以此来处理一些事件;

这里就写一下最近使用的一个很简单的方法:

首先建立一个TableView控件

- (void)viewDidLoad{    [super viewDidLoad];    self.mytableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight-29)style:UITableViewStylePlain];    self.mytableView.dataSource = self;    self.mytableView.delegate = self;    [self.view addSubview:self.mytableView];}

其中

//屏幕宽高#define  screenHeight [UIScreen mainScreen].bounds.size.height#define  screenWidth  [UIScreen mainScreen].bounds.size.width

然后实现tableView的DataSource和delegate里面的方法,本次测试选择了1组100行,这两个方法不再细写,列一下添加cell的方法以及在cell上添加button的代码

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    static NSString *Identifier = @"Mycell";    UITableViewCell * cell = [tableView  dequeueReusableCellWithIdentifier:Identifier];    if (cell == nil) {//重新实例化对象的时候才添加button,队列中已有的cell上面是有button的        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];        //添加按钮(或者其它控件)也可以写在继承自UITableViewCell的子类中,然后用子类来实例化这里的cell,将button作为子类的属性,这样添加button的触发事件的响应可以写在这里,target就是本类,方法也在本类中实现        UIButton* button=[UIButton buttonWithType:UIButtonTypeCustom];        button.frame=CGRectMake(screenWidth-100,5 ,80 , 30);        [button setTitle:@"button" forState:UIControlStateNormal];        [button setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];        button.layer.borderColor=[[UIColor orangeColor]CGColor];        button.layer.borderWidth=1;        button.layer.cornerRadius=5;        [button addTarget:self action:@selector(btAction:) forControlEvents:UIControlEventTouchUpInside];        [cell addSubview:button];    }    cell.selectionStyle = UITableViewCellSelectionStyleNone;        cell.textLabel.text=[NSString stringWithFormat:@"测试第%ld行",indexPath.row];        return cell;}



点击每行的响应方法

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{    NSLog(@"误操作");}

cell上的button的响应方法

-(void)btAction:(UIButton*)bt{    NSIndexPath *myIndex=[self.mytableView indexPathForCell:(UITableViewCell*)[bt superview]];    //如果按钮是加在cell上的contentView上    NSIndexPath *myIndex=[self.mytableView indexPathForCell:(UITableViewCell*)[[bt superview]superview]];    NSLog(@"myIndex.section==%ld",myIndex.section);    NSLog(@"myIndex.row==%ld",myIndex.row);}



是不是非常简单呢


0 0
原创粉丝点击