外部获取IndexPath的几种方式(关联对象等)
2017-02-08 14:19
525 查看
一、单击某个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]; } }
相关文章推荐
- 蓝桥杯 表达式计算 By Assassin
- Android Studio implements 一个类后如何实现这个类的方法
- Hibernate 一级缓存,二级缓存,查询缓存
- iOS quartzCore 学习之CALayer02
- Python学习札记(十九) 高级特性5 迭代器
- [Playframework+JPA+mysql] 数据更新与删除
- cocos-2dx开发项目中的热更新
- Database,Uva1592
- PHPExcel导出的问题,在PHP7中
- The working copy needs to be upgraded svn: The working copy at 'D:\eclipse workspace\kjzfcopy' is
- Android面试题(一)
- 怎么使用筛选法求素数
- 使用 gradle 进行 android 分包(dex)
- Python list 操作
- 中国互联网的二十年
- JS监测鼠标指针位置
- LeetCode Trapping Rain Water II
- 电商相关概念
- Spark经典案例5-求最大最小值
- 集合面试