Search code examples
iosswiftuiimageviewcollision-detection

Get current position of ImageView in swift


This is my very first time trying to build an app in swift so please excuse the fact that my understanding is very limited.


After I have added an ImageView to my ViewController, connected a Pan Gesture Recognition and added the code to be able to move the ImageView, which works just fine, I now want to be able to get the current coordinates of the middle of my ImageView when moving it. The goal is to able to calculate the euclidian distance between the middle of the screen and the middle of the ImageView, in order to detect collision with a Circle that is around the ImageView, but for now, just being able to print the coordinates would really help me. Thanks for any advice or tips on how I could approach this.

import UIKit

class ViewController: UIViewController {

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


    @IBOutlet weak var questImg: UIImageView!

    @IBAction func panMade(_ sender: UIPanGestureRecognizer) {
        if sender.state == .began || sender.state == .changed {
                   let translation = sender.translation(in: sender.view)
                   let changeX = (sender.view?.center.x)! + translation.x
                   let changeY = (sender.view?.center.y)! + translation.y

                   sender.view?.center = CGPoint(x: changeX, y: changeY)
                   sender.setTranslation(CGPoint.zero, in: sender.view)
    }

    }


}

Solution

  • To get the location of UIImageView you can use frame.origin like below:

    @IBAction func panMade(_ sender: UIPanGestureRecognizer) {
        if sender.state == .began || sender.state == .changed {
                   let translation = sender.translation(in: sender.view)
                   let changeX = (sender.view?.center.x)! + translation.x
                   let changeY = (sender.view?.center.y)! + translation.y
    
                   var coordX = questImg.frame.origin.x
                   var coordY = questImg.frame.origin.y
                   print(coordX + "," + coordY)
    
                   sender.view?.center = CGPoint(x: changeX, y: changeY)
                   sender.setTranslation(CGPoint.zero, in: sender.view)
    }