如何在Swift中将UILongPressGestureRecognizer与UICollectionViewCell一起使用? [英] How do I use UILongPressGestureRecognizer with a UICollectionViewCell in Swift?

查看:382
本文介绍了如何在Swift中将UILongPressGestureRecognizer与UICollectionViewCell一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to figure out how to println the indexPath of a UICollectionViewCell when I long press on a cell.

我如何在Swift中执行此操作?

How can I do that in Swift?

我已经看了一遍如何做到这一点;在Swift中找不到一个。

I have looked all over for an example of how to do this; can't find one in Swift.

推荐答案

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

First you your view controller need to be UIGestureRecognizerDelegate. 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 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")
        }
    }

此代码基于这个答案

这篇关于如何在Swift中将UILongPressGestureRecognizer与UICollectionViewCell一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆