我們在使用TableView時,默認有單擊或者側滑刪除等操作,但是原生的沒有長按操作。而來到CollectionView中,又少了一個側滑操作。在實際的項目開發中,我們需要使用單擊或者長按來進行不同的操作,並獲取cell的section和row。所以我們在CollectionView中來實現,在TableView中也是類似。
該demo我已經上傳到 https://github.com/chenyufeng1991/CollectionView 。裡面也包含了CollectionView的其他demo。我將在 https://github.com/chenyufeng1991/CollectionView/tree/master/CollectionView%E8%BF%9B%E9%98%B6%E2%80%94%E2%80%94%E8%8E%B7%E5%8F%96Cell%E4%B8%AD%E6%8C%89%E9%92%AE%E7%82%B9%E5%87%BB%E4%BA%8B%E4%BB%B6 。基礎上繼續進行。
(1)原生cell沒有長按事件,我們需要使用手勢識別來綁定CollectionView。創建並綁定CollectionView如下:
- (void)viewDidLoad { [super viewDidLoad]; /*
****
*/ //創建長按手勢監聽 UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(myHandleTableviewCellLongPressed:)]; longPress.minimumPressDuration = 1.0; //將長按手勢添加到需要實現長按操作的視圖裡 [self.collectionView addGestureRecognizer:longPress]; }
- (void) myHandleTableviewCellLongPressed:(UILongPressGestureRecognizer *)gestureRecognizer { CGPoint pointTouch = [gestureRecognizer locationInView:self.collectionView]; if (gestureRecognizer.state == UIGestureRecognizerStateBegan) { NSLog(@UIGestureRecognizerStateBegan); NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:pointTouch]; if (indexPath == nil) { NSLog(@空); }else{ NSLog(@Section = %ld,Row = %ld,(long)indexPath.section,(long)indexPath.row); } } if (gestureRecognizer.state == UIGestureRecognizerStateChanged) { NSLog(@UIGestureRecognizerStateChanged); } if (gestureRecognizer.state == UIGestureRecognizerStateEnded) { NSLog(@UIGestureRecognizerStateEnded); } }