IOS:长按选择UICollectionView单元格 [英] IOS: Selecting UICollectionView Cell by Long Press
本文介绍了IOS:长按选择UICollectionView单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 UICollectionView
来生成图片库。我在 UIImage
> UICollectionView 要加载图像的单元格。我需要选择 UICollectionView
按长按单元格(不是单击)。
I'm using UICollectionView
to generate a image gallery.I used UIImage
inside the UICollectionView
Cell to load the images.I need to select UICollectionView
Cell by Long Press (not by single tap).
- (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
First add UIGestureRecognizerDelegate to your view controller. Then add a UILongPressGestureRecognizer to your collectionView in your viewcontroller's viewDidLoad() method
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版本。
这篇关于IOS:长按选择UICollectionView单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文