segue取得cell中的按钮点击的行号

寵の児 提交于 2020-02-29 13:32:17

cell中点击分为两种方式,点击行跳转到主功能界面,点击cell上的button跳转的编辑界面,那么如何在点击button的时候知道所点击行的行号呢?解决办法是给button绑定tag:

// 自定义一个button
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame = CGRectMake(0, 0, 55, 25);
    btn.backgroundColor = [UIColor clearColor];
    btn.tag = indexPath.row;// 给按钮绑定tag,好知道点击的是哪行
    [btn setTitle:@"Edit" forState:UIControlStateNormal];
    
    [btn addTarget:self action:@selector(Edit:) forControlEvents:UIControlEventTouchUpInside];
    
    cell.accessoryView = btn;

在事件方法中传递button:

- (IBAction)Edit:(UIButton *)sender {
    // 执行sugue
    [self performSegueWithIdentifier:@"deviceList2edit" sender:sender];
}

在prepareForSegue:方法中获取button的tag:

// 跳转到编辑界面
        HHEditViewController *editVc = vc;
        
        // 根据button的tag取得选中的行
        editVc.device = self.device[sender.tag];
        
        editVc.delegate = self;

这种方式实现简单,但是也有弊端,设置button的tag在此处,但cell的重用机制,删除插入cell都可以使 indexPath 发生变化,而 tableView没有刷新,button的tag可能就不准确了,现阶段的解决办法是在删除cell后,再次刷新一次tableView。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!