Search code examples
iosswiftcoordinatescgrect

Get CGRect coordinates dynamically


I'm trying to get the distance between two UIImageView on my screen, and for that I planned on substracting the center coordinates of the image 2 (movable) from the image 1 (not movable). For that, I need to be able to get dynamically the coordinates of these images and I'm using something like this :

    var centerBoardX = CGRectGetMidX(BlackBoard.frame)
    var centerBoardY = CGRectGetMidY(BlackBoard.frame)
    var centerRoundX = CGRectGetMidX(round1.frame)
    var centerRoundY = CGRectGetMidY(round1.frame)

    println(centerBoardX - centerRoundX)
    println(centerBoardY - centerRoundY)

But even if I'm moving the image2 all over the screen I always get the same result based on the initial coordinates of both UIImageViews.

What's wrong ? Why do I get only the initial coordinates and not the new ones? Thanks !


Solution

  • OK, so I found what was not right. My UIImageViews are defined by frames, and I was getting the coordinates of the frame, which are always the same. To get the correct coordinates, I needed to get the info from the superview of the object. So the working code is

    var centerBoardX = BlackBoard.superview?.center.x
    var centerBoardY = BlackBoard.superview?.center.y
    var centerRoundX = Round1.superview?.center.x
    var centerRoundY = Round1.superview?.center.y
    
    println(centerBoardX! - centerRoundX!)
    println(centerBoardY! - centerRoundY!)
    

    And now it's perfectly working !