2016-04-24 63 views
0

我有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; 
} 

所以基本上我想通過指數throught action:@selector(aMethod)。怎麼做?

+1

你不能因爲方法簽名固定傳遞到amethod方法。你可以使用按鈕的標籤,因爲按鈕將作爲發送者發送給aMethod(選擇器將需要成爲'aMethod:'而不是'aMethod',但更簡潔的方法是按鈕成爲'IndexGridCollectionCell'的一部分,並且使用授權將按鈕操作返回給您的視圖控制器。 – Paulw11

回答

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 
+0

完美!正是我想要的!謝謝! –