通过选择器传递单元索引路径

时间:2016-04-24 14:25:42

标签: ios objective-c

我有UICollectionView,在每个单元格上我想添加一个按钮。单击此按钮时,我想删除特定索引处的单元格。问题是,我不知道如何传递选定的索引。这是我的cellForRow ..方法:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{   
    IndexGridCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];

    NSString *str = self.viewModel.arrValues[indexPath.row];
    [cell bindViewModel:str];
    cell.backgroundColor = [UIColor grayColor];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeContactAdd];
    [button addTarget:self
               action:@selector(aMethod)
     forControlEvents:UIControlEventTouchUpInside];
    [cell addSubview:button];

    [button mas_makeConstraints:^(MASConstraintMaker *make) {

        make.left.equalTo(cell.mas_left).with.offset(0);
        make.top.equalTo(cell.mas_top).with.offset(0);
        make.width.height.equalTo(@(20));

    }];

    return cell;
}

所以基本上我想通过action:@selector(aMethod)传递索引。怎么做?

1 个答案:

答案 0 :(得分:1)

如果只有一个部分你想获得索引,你可以添加你的UIButton像这样

UIButton *button = [UIButton buttonWithType:UIButtonTypeContactAdd];
[button addTarget:self
               action:@selector(aMethod:)
     forControlEvents:UIControlEventTouchUpInside];
[button setTag:indexPath.row];
[cell addSubview:button];

然后获取其标签号 -

-(void)aMethod:(UIButton *)sender
{
    NSLog(@"tag number is = %d",[sender tag]);
    //In this case the tag number of button will be same as your cellIndex.
   // You can make your cell from this.

   NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[sender tag] inSection:0];
   UITableViewCell *cell = [tblView cellForRowAtIndexPath:indexPath];
}

如果您有多个部分,可以尝试这样

选项:1

CGPoint touchPoint = [sender convertPoint:CGPointZero toView:tblView];
NSIndexPath *indexPath = [tblView indexPathForRowAtPoint:touchPoint];
UITableViewCell *cell = [tblView cellForRowAtIndexPath:indexPath];
NSIndexPath *indexPath = [tblView indexPathForCell:cell];//get the indexpath to delete the selected index 

选项:2

UIView *contentView = (UIView *)[sender superview];
UITableViewCell *cell = (UITableViewCell *)[contentView superview];//get the selected cell
NSIndexPath *indexPath = [tblView indexPathForCell:cell];//get the indexpath to delete the selected index