外部获取IndexPath的几种方式(关联对象等)

本文介绍两种在iOS中通过按钮点击事件获取UITableViewCell indexPath的方法:一种是常规方式,另一种是使用runtime关联对象的方式。同时,还提供了如何直接通过指定row来获取indexPath的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、单击某个cell中的button获取indexPath
1、 一般方式
- (void)buttonAction:(UIButton *)sender
     {
        UITableViewCell *cell = (UITableViewCell *)[[sender superview] superview]; 
        NSIndexPath *indexPath = [_tableView indexPathForCell:cell];  
        NSLog(@"indexPath is = %i",indexPath.row); 
     }

2、runtime添加属性方式,即关联对象的方式
//runtime 关联对象
     这种方式首先引入#import <objc/runtime.h>

     - (UITableViewCell *)tableView:(UITableView *)tableVie cellForRowAtIndexPath:(NSIndexPath *)indexPath
     {
         static NSString *identiStr = @"cellID";
         UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identiStr];
         if (cell == nil)
         {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identiStr];
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(0, 0, 100, 33);

            [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
            [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            button.tag = 110 + indexPath.row;
            [cell.contentView addSubview:button];
          }
          UIButton *button = (UIButton *)[cell.contentView viewWithTag:110];
         //runtime 关联对象
         objc_setAssociatedObject(button, @"button", indexPath, OBJC_ASSOCIATION_ASSIGN);
         [button setTitle:dataSource[indexPath.row] forState:UIControlStateNormal];

         return cell;     
     }
    //事件触发 runtime 获取关联的对象
     - (void)buttonAction:(UIButton *)sender
     {
        //runtime 获取关联的对象
        UITableViewCell *cell = objc_getAssociatedObject(sender, @"button");
        NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
        NSLog(@"indexPath is = %ld",indexPath.row);
     }
二、已知具体row,获取indexPath
- (void) refreshLessTime
{
    for (int row = 0; row < leftTimeArr.count; row ++)
    {
          NSIndexPath *indexPath = [NSIndexPath indexPathForItem: row inSection:0];
          UITableViewCell *cell = (UITableViewCell *)[_tableView cellForRowAtIndexPath:indexPath];
          UILabel *remainingTimeLabel = (UILabel *)[[cell.contentView viewWithTag:500] viewWithTag:501];
          remainingTimeLabel.text = [leftTimeArr objectAtIndex:indexPath.row];
     }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值