zoukankan      html  css  js  c++  java
  • 外部获取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];
    }
    }

  • 相关阅读:
    简单的方法爬取b站dnf视频封面步骤解释
    ROS讲座 关于ROS2和Gazebo C++ in Open Source Robotics
    深圳3分钟完成港澳签注 24小时自助办证服务攻略
    如何建立数据平台?看上市公司的选择!
    从开发转型到技术总监的迷茫
    计算机控制技术课程解释与问题答疑
    深度剖析 | 基于大数据架构的BI应用
    Android系统开机启动流程及init进程浅析
    经验分享 | 如何搭建企业管理驾驶舱
    android 修改framework下资源文件后如何编译
  • 原文地址:https://www.cnblogs.com/tangyuanby2/p/10236634.html
Copyright © 2011-2022 走看看