iOS進階開發——CollectionView的cell長按事件實現

來源:互聯網
上載者:User

iOS進階開發——CollectionView的cell長按事件實現

我們在使用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];}

(2)處理長按事件:

 

 

- (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);  }}

(3)運行程式,長按cell可以獲得該cell的indexPath.section和indexPath.row值。並且注意的是,長按事件和單擊事件並不會衝突,彼此沒有任何關係,這個是最開心的。這樣,我們把CollectionView的功能又進行了擴充。

 

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.