在 swift 中移动多图像 (UIPanGestureRecognizer)

Moving Multi image in swift (UIPanGestureRecognizer)

我是 swift 和 xcode 的新手。使用 xcode 10 并尝试制作一个像应用程序一样的嗡嗡声,我需要在视图中移动多个图像。我发现了很多关于 UIPanGestureRecognizerUITapGestureRecognizer 的信息,但所有这些都在为具有最后一个 addGestureRecognizerUIImage 工作,而不是为其余的工作。

有没有办法检测我正在触摸哪个 UIImage 以启用它的移动?

  1. 为每个图像视图添加一个标签(如有必要,维护标签和图像的字典)
  2. 在您的手势识别器中,获取用户触摸的图像视图。
  3. 获取该视图的标签以识别图像视图并相应地识别图像。

我找到了解决方案或者实际上我做错了什么:

您需要为每个UIImage定义一个新变量UIPanGestureRecognizer,该变量一次控制一个对象。

谢谢

这就是有效的方法

@IBOutlet var imagesToMove: [UIImageView]!


let imagesNames = ["chk", "unchk"]

var gesturePanArray: [UIPanGestureRecognizer] = []
var gestureTapArray: [UITapGestureRecognizer] = []

override func viewDidLoad() {
    super.viewDidLoad()
    var i = 0

    for imageItem in imagesToMove {
        imageItem.image = UIImage(named: imagesNames[0])

        imageItem.isUserInteractionEnabled = true
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(self.wasDragged(_:)))
        gesturePanArray.append(panGesture)
        imageItem.addGestureRecognizer(gesturePanArray[i])

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.wasTouched(_:)))

        gestureTapArray.append(tapGesture)
        imageItem.addGestureRecognizer(gestureTapArray[i])

        i = i + 1
    }

}

@objc func wasDragged(_ gesture: UIPanGestureRecognizer) {
    let translation = gesture.translation(in: self.view)
    let image = gesture.view

    view.bringSubviewToFront(image!)

    image!.center = CGPoint(x: (image?.center.x)! + translation.x, y: (image?.center.y)! + translation.y)
    gesture.setTranslation(CGPoint.zero, in: self.view)

}

@objc func wasTouched (_ gesture: UITapGestureRecognizer) {

    let imageTag = gesture.view?.tag
    if imagesToMove[imageTag! - 1].image == UIImage(named: imagesNames[0]) {
    imagesToMove[imageTag! - 1].image = UIImage(named: self.imagesNames[1])
    } else {
     imagesToMove[imageTag! - 1].image = UIImage(named: self.imagesNames[0])
    }
}

}