我在 UIImageView
上有一个标签,如下所示。
标签是可拖动、可平移和可捏合的。但是我一次只能做一个手势。例如,我想在捏合标签时拖动标签,就像在 Snapchat 和 Whatsapp 中的图像文本中一样。我的功能如下。在我搜索时,我认为我应该创建一个自定义手势识别器,但我不知道如何创建。有什么办法可以在不创建自定义识别器的情况下做到这一点?
在执行此操作时,我从这篇文章中得到了帮助:
Snapchat-like text on image
func handlePan(recognizer: UIPanGestureRecognizer) {
var translation = recognizer.translation(in: allview)
translation.x = max(translation.x, imageview.frame.minX - mylabel.frame.minX)
translation.x = min(translation.x, imageview.frame.maxX - mylabel.frame.maxX)
translation.y = max(translation.y, imageview.frame.minY - mylabel.frame.minY)
translation.y = min(translation.y, imageview.frame.maxY - mylabel.frame.maxY)
if let view = recognizer.view {
view.center = CGPoint(x:view.center.x + translation.x,
y:view.center.y + translation.y)
}
recognizer.setTranslation(CGPoint.zero , in: view)
}
func handlePinch(recognizer: UIPinchGestureRecognizer) {
if let view = recognizer.view as? UILabel {
let pinchScale: CGFloat = recognizer.scale
view.transform = view.transform.scaledBy(x: pinchScale, y: pinchScale)
recognizer.scale = 1.0
}
}
func handleRotate(recognizer: UIRotationGestureRecognizer) {
if let view = recognizer.view as? UILabel {
let rotation: CGFloat = recognizer.rotation
view.transform = view.transform.rotated(by: rotation)
recognizer.rotation = 0.0
}
}
最佳答案
我通过将“UIGestureRecognizerDelegate”添加到我的 ViewController 来解决。这允许同时使用手势。我确信创建自定义手势会更好,但这也能奏效。在 viewDidLoad 函数上添加这三行代码
pinchRecognizer.delegate = self
panRecognizer.delegate = self
rotateRecognizer.delegate = self
也不要忘记为委托(delegate)添加functin;
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
关于ios - 同时捏合、拖动和平移,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40934454/