很多時候,我們都需要在項目中添加長按手勢,比如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進行區分,這樣是不是很簡單