繁体   English   中英

使用UILongPressGestureRecognizer删除UICollectionViewCell

[英]Delete UICollectionViewCell with UILongPressGestureRecognizer

我有一个从图片库填充的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");
}
}

在你的情况下试试这个

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM