首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Swift中通过UICollectionViewCell使用UILongPressGestureRecognizer?

如何在Swift中通过UICollectionViewCell使用UILongPressGestureRecognizer?
EN

Stack Overflow用户
提问于 2015-03-25 03:55:33
回答 6查看 31.1K关注 0票数 24

当我长按一个单元格时,我想知道如何打印UICollectionViewCell的indexPath。

我如何在Swift中做到这一点?

我到处寻找如何做到这一点的例子,但在Swift中找不到。

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2015-03-25 05:11:51

首先,您的视图控制器需要是UIGestureRecognizerDelegate。然后在视图控制器的viewDidLoad()方法中向collectionView添加一个UILongPressGestureRecognizer

代码语言:javascript
复制
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)
    }

处理长按的方法:

代码语言:javascript
复制
func handleLongPress(gestureReconizer: UILongPressGestureRecognizer) {
        if gestureReconizer.state != UIGestureRecognizerState.Ended {
            return
        }

        let p = gestureReconizer.locationInView(self.collectionView)
        let indexPath = self.collectionView.indexPathForItemAtPoint(p)

        if let index = indexPath {
            var cell = self.collectionView.cellForItemAtIndexPath(index)
            // do stuff with your cell, for example print the indexPath
             println(index.row)
        } else {
            println("Could not find index path")
        }
    }

此代码基于this answer的Objective-C版本。

票数 63
EN

Stack Overflow用户

发布于 2016-11-11 20:28:53

ztan答案已转换为swift 3语法和次要拼写更新:

代码语言:javascript
复制
func handleLongPress(_ gestureRecognizer: UILongPressGestureRecognizer) {
    if gestureRecognizer.state != UIGestureRecognizerState.ended {
      return
    }

    let p = gestureRecognizer.location(in: collectionView)
    let indexPath = collectionView.indexPathForItem(at: p)

    if let index = indexPath {
      var cell = collectionView.cellForItem(at: index)
      // do stuff with your cell, for example print the indexPath
      print(index.row)
    } else {
      print("Could not find index path")
    }
}
票数 10
EN

Stack Overflow用户

发布于 2016-04-14 03:14:29

我发现的一件事是:

代码语言:javascript
复制
if gestureReconizer.state != UIGestureRecognizerState.Ended {
    return
}

在你松开长按键之前不会放大头针,这是可以的,但我发现

代码语言:javascript
复制
if gestureRecognizer.state == UIGestureRecognizerState.Began { }  

整个功能将防止多个引脚放置,同时让引脚在满足计时器延迟的情况下立即出现。

还有,上面的一个打字错误:校正器->识别器

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29241691

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档