使用UILongPressGestureRecognizer删除UICollectionViewCell

时间:2015-01-14 09:33:40

标签: ios objective-c uicollectionview uicollectionviewcell

我有一个UICollectionView我从我的图片库填充。

我希望能够通过在单元格上使用UILongPressGestureRecognizer从集合中删除单元格。 UILongPressGestureRecognizer正在运作。

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"Selected cell = %ld",(long)indexPath.item);

UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(activateDeletionMode:)];
longPress.delegate = self;
[collectionView addGestureRecognizer:longPress];

}

- (void)activateDeletionMode:(UILongPressGestureRecognizer *)gr
{
if (gr.state == UIGestureRecognizerStateBegan)
{
NSLog(@"delete mode");
}
}

1 个答案:

答案 0 :(得分:0)

在你的情况下试试这个

    - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
    {
    NSLog(@"Selected cell = %ld",(long)indexPath.item);

     UILongPressGestureRecognizer * longPres 
       = [[UILongPressGestureRecognizer alloc]
                     initWithTarget:self action:@selector(activateDeletionMode:)];
   longPres.minimumPressDuration = .5; //seconds
   longPres.delegate = self;
    [self.collectionView addGestureRecognizer: longPres];


    }

    - (void)activateDeletionMode:(UILongPressGestureRecognizer *)gr
    {
    if (gr.state == UIGestureRecognizerStateBegan)
    {
    NSLog(@"delete mode");
    }
    }

在其他情况下,你可以试试这个

//将长按手势添加到collectionView

 UILongPressGestureRecognizer *longpress 
       = [[UILongPressGestureRecognizer alloc]
                     initWithTarget:self action:@selector(handleLongpressMethod:)];
    longpress.minimumPressDuration = .5; //seconds
   longpress.delegate = self;
    [self.collectionView addGestureRecognizer: longpress];
}

然后处理行动

-(void) handleLongpressMethod:(UILongPressGestureRecognizer *)gestureRecognizer
{
    if (gestureRecognizer.state != UIGestureRecognizerStateEnded) {
        return;
    }
    CGPoint pt = [gestureRecognizer locationInView:self.collectionView];

    NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:pt];
    if (indexPath == nil){
        NSLog(@"couldn't find index path");            
    } else {
        // get the cell at indexPath (the one you long pressed)
        UICollectionViewCell* cell =
        [self.collectionView cellForItemAtIndexPath:indexPath];
        // work  with the cell


    }

删除

 [self.youritemarray removeObjectAtIndex:indexPathh];
 [collectionView reloadData];