Swift version: 5.2
Each view has its own co-ordinate system, meaning that if I tap a button and ask iOS where I tapped, it will tell me where I tapped relative to the top-left of the button. This is usually what you want, but if you want to translate a position in one view into a position it's easy enough to do.
As an example, this code creates two views, creates a virtual "tap", then converts it from the first view's co-ordinate space to the second's:
let view1 = UIView(frame: CGRect(x: 50, y: 50, width: 128, height: 128)) let view2 = UIView(frame: CGRect(x: 200, y: 200, width: 128, height: 128)) let tap = CGPoint(x: 10, y: 10) let convertedTap = view1.convert(tap, to: view2)
That will set
convertedTap to X -140.0, Y -140.0.
SPONSORED Announcing NSSpain 2020: Remote Edition! An online, continuous conference for iOS developers. We’ll start on Thursday and finish on Friday, with talks, activities, and lots of fun for 36 hours, non-stop. Sound good? Join us!
Available from iOS 2.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.