快速移动多张图像(UIPanGestureRecognizer)

时间:2019-02-09 13:03:56

标签: ios swift xcode10.1

我是swift和xcode的新手。使用xcode 10并尝试制作类似app的嗡嗡声,我需要在视图中移动多个图像。我发现了很多有关UIPanGestureRecognizerUITapGestureRecognizer的信息,但是它们都为最后一个UIImage的{​​{1}}工作,而其余的都不工作。

是否可以检测到我正在触摸哪个addGestureRecognizer以使其移动?

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

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

谢谢

这是有效的

@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])
    }
}

}