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

标签 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) 传递索引。如何做到这一点?

最佳答案

如果只有一个部分你想得到你可以添加你的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

关于ios - 通过选择器传递单元格索引路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36824365/

相关文章:

ios - Xcode 4.6.3 中的解析问题 - "Expected a type"- 找不到错误

ios - 获取接触点位置

ios - Swift NSString 函数语法用法

iOS:发送缓冲区中的套接字连接错误

iPhone App - 关闭模态视图 Controller 不会释放它

objective-c - 从 NSMutableArray 获取双倍值

c - 关于 Objective-C 中指针的问题

ios - RestKit 和 Cocoapods : Mapping operation failed/did not find any mappable values

iphone - 安排与外部 UIView 相关的 UIView subview

iphone - 我该如何限制 ipad 中的文件应用程序大小?