如何得到自定义UITableViewCell中的按钮所在的cell的indexPath.row

在iOS7下面已经无效,因为iOS7的层级关系发生变化

UITableViewCell->UITableViewCellScrollView->UITableViewCellContentView->Your custom view

下面有2种方法解决这个问题

-(void) visitButtonClicked:(UIButton *)sender

{

    // 第一种,兼容所有的版本

    UIView *superView = sender.superview;

    UITableViewCell *foundSuperView = nil;

    

    while (nil != superView && nil == foundSuperView) {

        if ([superView isKindOfClass:[UITableViewCell class]]) {

            foundSuperView = (UITableViewCell *)superView;

        } else {

            superView = superView.superview;

        }

    }

    NSLog(@"founda = %d", [_tableView indexPathForCell:foundSuperView].row);

   

    // 2种,不兼容iOS7以下

    UITableViewCell *cell = (UITableViewCell *)[[[sender superviewsuperviewsuperview];

    

    NSLog(@"foundb = %d", [_tableView indexPathForCell:cell].row);

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的示例代码,演示如何在UITableView修改单元格的内容: 首先,你需要实现UITableViewDataSource协议的tableView(_:cellForRowAt:)方法,该方法用于配置单元格并返回UITableViewCell对象。 在这个方法,你可以设置单元格的文本标签、图像等属性。当你需要更改单元格内容时,可以通过访问单元格的标签和其他视图来执行此操作。 例如,下面的代码显示如何在单元格显示一个数字,并在用户点击单元格时将其增加1: ``` class MyTableViewController: UITableViewController { var numbers = [1, 2, 3, 4, 5] override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return numbers.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) // 设置单元格的文本标签为数字 cell.textLabel?.text = "\(numbers[indexPath.row])" return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // 将单元格的数字增加1 numbers[indexPath.row] += 1 // 获取单元格并更新标签 let cell = tableView.cellForRow(at: indexPath) cell?.textLabel?.text = "\(numbers[indexPath.row])" } } ``` 在这个示例,我们首先在MyTableViewController类定义了一个numbers数组,用于存储要显示在UITableView的数字。在tableView(_:cellForRowAt:)方法,我们设置了单元格的文本标签为相应的数字。 当用户点击单元格时,didSelectRowAt方法会被调用。在这个方法,我们将单元格的数字增加1,并使用tableView(_:cellForRow:)方法获取单元格并更新其标签。 需要注意的是,如果你想在UITableView更新单元格的内容,你必须使用UITableViewcellForRow(at:)方法获取单元格对象,然后使用它来更新单元格的内容。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值