如何获得在UICollectionView选择CollectionViewCell?(How to

2019-10-20 07:45发布

我是新的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 cellcollectionView

Answer 1:

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

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]];
    }];
}


Answer 2:

对于被点击它收集细胞检查,您可以使用您的控制器此委托方法。

-(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;
        }
        .
        .
        .
    }
}


文章来源: How to get the selected CollectionViewCell in the UICollectionView?