ios 如何在 Swift 中将 UILongPressGestureRecognizer 与 UICollectionViewCell 一起使用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29241691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 05:19:24  来源:igfitidea点击:

How do I use UILongPressGestureRecognizer with a UICollectionViewCell in Swift?

iosswiftuigesturerecognizeruicollectionviewcell

提问by webmagnets

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

我想弄清楚当我长按一个单元格时如何打印 UICollectionViewCell 的 indexPath 。

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.

我已经四处寻找如何做到这一点的例子;在 Swift 中找不到。

回答by ztan

First you your view controller need to be UIGestureRecognizerDelegate. Then add a UILongPressGestureRecognizer to your collectionView in your viewcontroller's viewDidLoad()method

首先,您的视图控制器需要是UIGestureRecognizerDelegate. 然后在您的视图控制器的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)
    }

The method to handle long press:

处理长按的方法:

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 code is based on the Objective-C version of this answer.

此代码基于此答案的 Objective-C 版本。

回答by chr0x

ztan answer's converted to swift 3 syntax and minor spelling update:

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

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

回答by DPen

One thing I found was that:

我发现的一件事是:

if gestureReconizer.state != UIGestureRecognizerState.Ended {
    return
}

doesn't place pin until you release the longpress, which is OK, but I found

在你松开长按之前不会放置别针,这没关系,但我发现

if gestureRecognizer.state == UIGestureRecognizerState.Began { }  

around the whole function will prevent multiple pin placements while letting the pin appear as soon as the timer delay is satisfied.

围绕整个功能将防止多个引脚放置,同时让引脚在定时器延迟满足后立即出现。

Also, one typo above: Reconizer -> Recognizer

另外,上面有一个错字:Reconizer -> Recognizer

回答by Fernando Cardenas

The method handleLongProgress converted to swift 3 syntax works fine. I just want to add that the initialization of lpgr should be changed to:

转换为 swift 3 语法的方法 handleLongProgress 工作正常。我只想补充一下lpgr的初始化应该改为:

let lpgr = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(gestureReconizer:)))

回答by Shakeel Ahmed

Swift 5 & Swift 4 Table View Cell

Swift 5 & Swift 4 表格视图单元格

override func viewDidLoad() {
    //MARK:- Add Long Gesture
    let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressed))
    longPressGesture.minimumPressDuration = 1.0 // 1 second press
    longPressGesture.allowableMovement = 15 // 15 points
    longPressGesture.delegate = self
    self.tablev.addGestureRecognizer(longPressGesture)
}


//MARK:- Long Press Gesture
@objc func longPressed(sender: UILongPressGestureRecognizer)
{

    if sender.state == UIGestureRecognizer.State.ended {
        return
    }
    else if sender.state == UIGestureRecognizer.State.began
    {
        let p = sender.location(in: self.tablev)
        let indexPath = self.tablev.indexPathForRow(at: p)

        if let index = indexPath {
            var cell = self.tablev.cellForRow(at: index)
            // do stuff with your cell, for example print the indexPath
            print(index.row)
            print("longpressed Tag: \(index.row)")
        } else {
            print("Could not find index path")
        }
    }
}

回答by Cosmo Arun

if objc func calling causes an error (Swift 5),

如果 objc func 调用导致错误(Swift 5),

Replace Selector("handleLongPress")with #selector(self. handleLongPress)here is the full implementation.

替换Selector("handleLongPress")#selector(self. handleLongPress)这里是完整的实现。

in your viewDidLoad(),

在您的 viewDidLoad() 中,

        let lpgr = UILongPressGestureRecognizer(target: self, 
                             action:#selector(self.handleLongPress))
        lpgr.minimumPressDuration = 1
        lpgr.delaysTouchesBegan = true
        lpgr.delegate = self
        self._mapView.addGestureRecognizer(lpgr)

and implement this in your viewcontroller,

并在您的视图控制器中实现这一点,

@objc func handleLongPress(gestureRecognizer: 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")
    }

 }

回答by Artem

ztan answer's converted to swift 4 syntax and minor spelling update:

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

@objc func handleLongPress(_ gestureRecognizer: UILongPressGestureRecognizer) {
    guard gestureRecognizer.state != .ended else { return }

    let point = gestureRecognizer.location(in: collectionView)

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