我有 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/