UIImageView 转换丢失滑动手势

UIImageView transform loses swipe gesture

我有一张图片,每次用户在上面滑动时我都想旋转它。它第一次起作用,而且只有第一次!视图如何丢失滑动手势识别器?

        myCircle = UIImageView( ... )
        myCircle.isUserInteractionEnabled = true

        let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(swiping(sender:)))
        swipeLeft.direction = .left
        myCircle.addGestureRecognizer(swipeLeft)
        let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(swiping(sender:)))
        swipeRight.direction = .right
        myCircle.addGestureRecognizer(swipeRight)
    }

    @objc func swiping(sender: UISwipeGestureRecognizer) {
        // this function only called the first time!
        if sender.direction == UISwipeGestureRecognizer.Direction.left {
            myCircleRotation -= CGFloat(Double.pi/2)
        } else if sender.direction == UISwipeGestureRecognizer.Direction.right {
            myCircleRotation += CGFloat(Double.pi/2)
        }
        // if I comment out this next line, function is called (correctly) every swipe!
        myCircle.transform = CGAffineTransform(rotationAngle: myCircleRotation)
    }

您可以将 UIView 作为容器视图添加到层​​次结构中,然后将 UIGestureRecognizer 添加到容器视图而不是 UIImageView。这将使您的图像旋转而不会影响手势。

import UIKit

class ImageViewController: UIViewController {

    @IBOutlet weak var myCircleView: UIImageView!
    @IBOutlet weak var containerView: UIView!

    var myCircleRotation:CGFloat = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        setupImage()
    }

    private func setupImage() {
        let image = UIImage(named: "your-image")
        myCircleView.image = image
        myCircleView.isUserInteractionEnabled = true

        let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(swiping(sender:)))
        swipeLeft.direction = .left
        containerView.addGestureRecognizer(swipeLeft)
        let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(swiping(sender:)))
        swipeRight.direction = .right
        containerView.addGestureRecognizer(swipeRight)
    }

    @objc func swiping(sender: UISwipeGestureRecognizer) {
        // this function only called the first time!
        if sender.direction == UISwipeGestureRecognizer.Direction.left {
            myCircleRotation -= CGFloat(Double.pi/2)
        } else if sender.direction == UISwipeGestureRecognizer.Direction.right {
            myCircleRotation += CGFloat(Double.pi/2)
        }

        UIView.animate(withDuration: 0.5) {
            self.myCircleView.transform = CGAffineTransform(rotationAngle: self.myCircleRotation)
        }
    }
}