外部獲取IndexPath的幾種方式(關(guān)聯(lián)對(duì)象等)
2019-11-09 15:53:54
供稿:網(wǎng)友
一、單擊某個(gè)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添加屬性方式,即關(guān)聯(lián)對(duì)象的方式
//runtime 關(guān)聯(lián)對(duì)象 這種方式首先引入#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 關(guān)聯(lián)對(duì)象 objc_setAssociatedObject(button, @"button", indexPath, OBJC_ASSOCIATION_ASSIGN); [button setTitle:dataSource[indexPath.row] forState:UIControlStateNormal]; return cell; } //事件觸發(fā) runtime 獲取關(guān)聯(lián)的對(duì)象 - (void)buttonAction:(UIButton *)sender { //runtime 獲取關(guān)聯(lián)的對(duì)象 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]; }}