Skip to content

Instantly share code, notes, and snippets.

@zenangst
Last active May 24, 2018 05:28
Show Gist options
  • Save zenangst/c07794931a248a3626b65faebcdaba2b to your computer and use it in GitHub Desktop.
Save zenangst/c07794931a248a3626b65faebcdaba2b to your computer and use it in GitHub Desktop.
Converting between view coordinate systems - Example 1
import UIKit
let frame = CGRect(origin: .zero,
size: .init(width: 150, height: 150))
let window = UIWindow(frame: frame)
let rootView = UIView(frame: window.bounds)
rootView.backgroundColor = .white
window.addSubview(rootView)
let view = UIView(frame: CGRect(origin: .init(x: 25, y: 25),
size: CGSize(width: 100, height: 100)))
view.backgroundColor = UIColor.green.withAlphaComponent(0.5)
rootView.addSubview(view)
let subview = UIView(frame: CGRect(origin: .init(x: 25, y: 25),
size: .init(width: 50, height: 50)))
subview.backgroundColor = UIColor.blue.withAlphaComponent(0.5)
view.addSubview(subview)
let convertToWindow = subview.convert(subview.bounds, to: window)
// {x 25 y 25 w 50 h 50 }
subview.frame
// {x 50 y 50 w 50 h 50 }
convertToWindow
window.makeKeyAndVisible()
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = window
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment