我是swift和xcode的新手。使用xcode 10
并尝试制作类似app的嗡嗡声,我需要在视图中移动多个图像。我发现了很多有关UIPanGestureRecognizer
和UITapGestureRecognizer
的信息,但是它们都为最后一个UIImage
的{{1}}工作,而其余的都不工作。
是否可以检测到我正在触摸哪个addGestureRecognizer
以使其移动?
答案 0 :(得分:0)
答案 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])
}
}
}