IOS:长按选择UICollectionView单元格

我正在使用UICollectionView生成一个UICollectionView我在UICollectionView Cell中使用了UIImage来加载图像。我需要通过长按选择UICollectionView Cell(而不是单击)。

 - (IBAction)longPress:(UILongPressGestureRecognizer *)gestureRecognizer { UICollectionViewCell *cell=(UICollectionViewCell *)[gestureRecognizer view]; int index=cell.tag; OverlayImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height)]; OverlayImage.image = [UIImage imageNamed:@"Overlay@2x.png"]; [cell addSubview:OverlayImage]; } 

首先将UIGestureRecognizerDelegate添加到视图控制器。 然后在viewcontroller的viewDidLoad()方法中为您的collectionView添加一个UILongPressGestureRecognizer

 class ViewController: UIViewController, UIGestureRecognizerDelegate { override func viewDidLoad() { super.viewDidLoad() let lpgr = UILongPressGestureRecognizer(target: self, action: "handleLongPress:") lpgr.minimumPressDuration = 0.5 lpgr.delaysTouchesBegan = true lpgr.delegate = self self.collectionView.addGestureRecognizer(lpgr) } 

处理长按的方法:

  func handleLongPress(gestureReconizer: UILongPressGestureRecognizer) { if gestureReconizer.state != UIGestureRecognizerState.Ended { return } let point = gestureReconizer.locationInView(self.collectionView) let indexPath = self.collectionView.indexPathForItemAtPoint(point) if let index = indexPath { var cell = self.collectionView.cellForItemAtIndexPath(index) // do stuff with your cell, for example print the indexPath print(index.row) } else { print("Could not find index path") } } 

此代码基于此答案的Objective-C版本。

斯威夫特4

更新了它的答案

 { let longPressGR = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(longPressGR:))) longPressGR.minimumPressDuration = 0.5 longPressGR.delaysTouchesBegan = true self.collectionView.addGestureRecognizer(longPressGR) } @objc func handleLongPress(longPressGR: UILongPressGestureRecognizer) { if longPressGR.state != .ended { return } let point = longPressGR.location(in: self.collectionView) let indexPath = self.collectionView.indexPathForItem(at: point) if let indexPath = indexPath { var cell = self.collectionView.cellForItem(at: indexPath) print(indexPath.row) } else { print("Could not find index path") } } 

你可以使用LongPressGesture

 UILongPressGestureRecognizer *longpressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressHandler:)]; longpressGesture.minimumPressDuration = 5; [longpressGesture setDelegate:self]; [self.yourImage addGestureRecognizer:longpressGesture]; - (void)longPressHandler:(UILongPressGestureRecognizer *)gestureRecognizer { NSLog(@"longPressHandler"); UIImageView *tempImage=(UIImageView*)[gestureRecognizer view]; }