问题描述
我想知道如何将长按手势识别器添加到 UICollectionView(的子类).我在文档中读到它是默认添加的,但我不知道如何.
I was wondering how to add a long press gesture recognizer to a (subclass of) UICollectionView. I read in the documentation that it is added by default, but I can't figure out how.
我想做的是:长按一个单元格(我有一个来自 github 的日历),获取点击了哪个单元格,然后对其进行处理.我需要知道长按的是哪个单元格.抱歉这个广泛的问题,但我在谷歌或 SO 上找不到更好的东西
What I want to do is: Long press on a cell ( I have a calendar thingy from github ), get which cell is tapped and then do stuff with it. I need to know what cell is longpressed. Sorry for this broad question, but i couldn't find anything better on either google or SO
推荐答案
Objective-C
在您的 myCollectionViewController.h
文件中添加 UIGestureRecognizerDelegate
协议
@interface myCollectionViewController : UICollectionViewController<UIGestureRecognizerDelegate>
在您的 myCollectionViewController.m
文件中:
- (void)viewDidLoad
{
// attach long press gesture to collectionView
UILongPressGestureRecognizer *lpgr
= [[UILongPressGestureRecognizer alloc]
initWithTarget:self action:@selector(handleLongPress:)];
lpgr.delegate = self;
lpgr.delaysTouchesBegan = YES;
[self.collectionView addGestureRecognizer:lpgr];
}
-(void)handleLongPress:(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
}
}
斯威夫特
class Some {
@objc func handleLongPress(gesture : UILongPressGestureRecognizer!) {
if gesture.state != .Ended {
return
}
let p = gesture.locationInView(self.collectionView)
if let indexPath = self.collectionView.indexPathForItemAtPoint(p) {
// get the cell at indexPath (the one you long pressed)
let cell = self.collectionView.cellForItemAtIndexPath(indexPath)
// do stuff with the cell
} else {
print("couldn't find index path")
}
}
}
let some = Some()
let lpgr = UILongPressGestureRecognizer(target: some, action: #selector(Some.handleLongPress))
斯威夫特 4
class Some {
@objc func handleLongPress(gesture : UILongPressGestureRecognizer!) {
if gesture.state != .ended {
return
}
let p = gesture.location(in: self.collectionView)
if let indexPath = self.collectionView.indexPathForItem(at: p) {
// get the cell at indexPath (the one you long pressed)
let cell = self.collectionView.cellForItem(at: indexPath)
// do stuff with the cell
} else {
print("couldn't find index path")
}
}
}
let some = Some()
let lpgr = UILongPressGestureRecognizer(target: some, action: #selector(Some.handleLongPress))
这篇关于UICollectionViewCell 上的长按手势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!