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


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

查看所有标签

猜你喜欢:

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

Wireshark网络分析就这么简单

Wireshark网络分析就这么简单

林沛满 / 人民邮电出版社 / 2014-11-6 / 39.00

Wireshark可能是世界上最好的开源网络包分析器,能在多种平台上(比如Windows、Linux和Mac)抓取和分析网络包,在IT业界有着广泛的应用。 《Wireshark网络分析就这么简单》采用诙谐风趣的手法,由浅入深地用Wireshark分析了常见的网络协议,读者在学习Wireshark的同时,也会在不知不觉中理解这些协议。作者还通过身边发生的一些真实案例,分享了Wireshark的......一起来看看 《Wireshark网络分析就这么简单》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具