UICollectionView添加長按手勢,長按選中某一個item


很多時候,我們都需要在項目中添加長按手勢,比如UICollectionView中,我們長按對某一個item進行刪除,那么這時,我們就需要在集合試圖中添加長按的手勢,手勢的添加是簡單的,但是添加過手勢之后,我們怎么區分我們長按選中的是哪一個item呢

首先,我們先來看看我們是如何添加長按手勢的

1.創建集合試圖,這個就比較簡單了.創建完集合試圖,我們在集合試圖上面添加長按的手勢

UIGestureRecognizerDelegate 先遵從協議

longPressGr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressToDo:)];
    longPressGr.minimumPressDuration = 1.0;
    longPressGr.delegate = self;
    longPressGr.delaysTouchesBegan = YES;
    [_myCollectionView addGestureRecognizer:longPressGr];

2.我們在longpressToDo里面添加方法

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

    NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:p];
    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];
        // do stuff with the cell
    }
}

在else里面我們根據indexpath對不同的item進行區分,這樣是不是很簡單

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM