ios – 如何在Swift的UICollectionViewCell中使用UILongPressGestureRecognizer?

栏目: Swift · 发布时间: 7年前

内容简介:当我长时间按下一个单元格时,我想知道如何打印一个UICollectionViewCell的indexPath.如何在Swift中做到这一点?我已经看了一遍如何做到这一点的例子;在斯威夫特找不到一个.

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

如何在Swift中做到这一点?

我已经看了一遍如何做到这一点的例子;在斯威夫特找不到一个.

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

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")
        }
    }

该代码基于Objective-C版本的 this answer .

代码日志版权声明:

翻译自:http://stackoverflow.com/questions/29241691/how-do-i-use-uilongpressgesturerecognizer-with-a-uicollectionviewcell-in-swift


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

RESTful Web Services Cookbook

RESTful Web Services Cookbook

Subbu Allamaraju / Yahoo Press / 2010-3-11 / USD 39.99

While the REST design philosophy has captured the imagination of web and enterprise developers alike, using this approach to develop real web services is no picnic. This cookbook includes more than 10......一起来看看 《RESTful Web Services Cookbook》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试