Swift: 获取 UIPanGestureRecognizer 的目标

Swift: Getting target of UIPanGestureRecognizer

在我的 ViewController.swift 中,我有一个包含自定义 UIView 的数组。每次创建一个时,我都会像这样向其添加一个 UIPanGestureRecognizer:

var panRecognizer = UIPanGestureRecognizer(target: self, action: "detectPan:")
newCard.gestureRecognizers = [panRecognizer]

这链接到我的 detectPan(recognizer: UIPanGestureRecognizer) 函数,它处理移动。但是,由于我有多个对象链接到函数,我不确定如何确定输入来自哪个对象。

我可以使用类似(不存在的)recognizer.target 的东西吗?我应该只处理每个自定义 UIView 中的平移吗?

如有任何帮助,我们将不胜感激!

首先,您应该用 let 声明您的 panRecognizer

let panRecognizer = UIPanGestureRecognizer(target: self, action: "detectPan:")

其次,您不应该设置任何 UIViewgestureRecognizers 属性。这是一种不好的做法,因为 UIKit 可能已经在幕后向该视图添加了自己的手势识别器。如果您随后通过将 [panRecognizer] 分配给 属性 来删除这些识别器,您可能会遇到意外行为。要添加平移手势识别器,请执行以下操作:

newCard.addGestureRecognizer(panRecognizer)

然后,在您的 detectPan(recognizer: UIPanGestureRecognizer) 方法中,您可以使用以下代码检测哪个 UIView 被平移:

func detectPan(recognizer: UIPanGestureRecognizer) {
    switch recognizer.view {
    case self.customViewArray[0]:
        // do something
    case self.customViewArray[1]:
        // do something else
    case ... :
    // ...
}