如何在UICollectionView中获取所选的CollectionViewCell?

时间:2014-06-19 04:07:19

标签: ios objective-c uicollectionview uicollectionviewcell

我是IOS开发的新手,我尝试使用UIcollectionView来显示照片而不使用storyboard

我创建了xib file来电AITFileCell_grid.xib,并添加了Collection View Cell

我还创建了另一个xib file并添加Collection View以加载Collection View Cell

我想选择多个文件并按delete button删除它们。

但是当我通过以下代码点击delete button时,我无法获取单元格。

if(self.collectionView.indexPathsForSelectedItems > 0){
        NSLog(@"indexPathsForSelectedItems...count.%@..@@@" , self.collectionView.indexPathsForSelectedItems);


        for(NSIndexPath *indexPath in self.collectionView.indexPathsForSelectedItems){

//            [self.collectionView deselectItemAtIndexPath:indexPath animated:NO];
            NSString *filePath = [NSString stringWithFormat:@"%@/%@", directory, [fileList objectAtIndex:indexPath.row]];
            [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil] ;
            AITFileCell_grid *cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:@"AITFileCell_grid" forIndexPath:indexPath];
        }
    }

但卖出似乎不正确......

如何在selected cell 中获取collectionView

2 个答案:

答案 0 :(得分:2)

通常你的删除按钮应该有这样的选择器:

deleteButton = [[UIButton alloc] init];
...
[deleteButton addTarget:self selector:@sel(buttonPressed:) forControlEvent:UIControlEventTouchUpInside];

我相信您可以使用以下命令获取indexPath:

-(void)buttonPressed:(id)sender
{
    UIButton *button = (UIButton *)sender;

    CGPoint rootPoint = [button convertPoint:CGPointZero toView:self.collectionView];

    NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:rootPoint];

    // -----------------------------------------------------------------
    // Now you have your indexPath, you can delete your item
    // -----------------------------------------------------------------



    // first update your data source, in this case, I assume your data source 
    // is a list of values stored inside a NSArray

    NSMutableArray *updatedList = [self.myListData mutableCopy];

    [updatedList removeObjectAtIndex:indexPath.row];

    self.myListData = updatedList;


    // now update your interface

    [self.collectionView performBatchUpdates:^{
        [self.collectionView deleteItemsAtIndexPath:@[indexPath]];
    }];
}

答案 1 :(得分:1)

要检查单击哪个Collection Cell,您可以在Controller中使用此委托方法。

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    int itemNo = (int)[indexPath row]+1;
    CollectionCell *selectedCell =(CollectionCell*)[collectionView cellForItemAtIndexPath:indexPath];
    switch (itemNo) {
        case 1:
        {
            //your Logic for 1st Cell
            break;
        }
        case 2:
        {
            //your Logic for 2nd Cell
            break;
        }
        .
        .
        .
    }
}