Search code examples
iosswiftvalue-type

Swift: restoring UIView center after moving it


I'm using gestures to zoom and move a UIImageView (like Instagram zoom, for example). When the gesture ends, I want to restore UIImageView initial position, but I cannot get a copy of the initial center because it's a reference type. Using:

let prevCenter = myImage.center

is of course useless. How can I copy it?


Solution

  • On zoom and move apply transform to view. On the end just set .identity value.

    Edit

    Example:

    @IBOutlet weak var butt: UIButton!
    
    var offsetTransform: CGAffineTransform = .identity
    var zoomTransform: CGAffineTransform = .identity
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    
        let pan = UIPanGestureRecognizer(target: self, action: #selector(onPan(pan:)))
        pan.minimumNumberOfTouches = 2
        pan.delegate = self
        view.addGestureRecognizer(pan)
    
        let pinch = UIPinchGestureRecognizer(target: self, action: #selector(onPinch(pinch:)))
        pinch.delegate = self
        view.addGestureRecognizer(pinch)
    }
    
    @objc func onPinch(pinch: UIPinchGestureRecognizer) {
        let s = pinch.scale
        zoomTransform = CGAffineTransform(scaleX: s, y: s)
        butt.transform = offsetTransform.concatenating(zoomTransform)
        if (pinch.state == .ended) {
            finish()
        }
    }
    
    @objc func onPan(pan: UIPanGestureRecognizer) {
        let t = pan.translation(in: view)
        offsetTransform = CGAffineTransform(translationX: t.x, y: t.y)
    }
    
    func updatePos() {
        butt.transform = offsetTransform.concatenating(zoomTransform)
    }
    
    func finish() {
        butt.transform = .identity
    }
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }