同时捏合、拖动和平移

Pinch, drag and pan at the same time

我在 UIImageView 上有一个标签,如下所示。

标签可拖动、可平移和可收缩。但是我一次只能做一个手势。例如,我想在捏住标签时拖动标签,就像在 Snapchat 和 Whatsapp 中的图像上的文本一样。我的功能如下。在我搜索时,我认为我应该创建一个自定义手势识别器,但我不知道如何创建。有没有什么方法可以在不创建自定义识别器的情况下做到这一点?

我在执行此操作时得到了此 post 的帮助:

 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

同时不要忘记为委托添加函数;

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}