iPhone - Get Position of UIView within entire UIWindow
That's an easy one:
[aView convertPoint:localPosition toView:nil];
... converts a point in local coordinate space to window coordinates. You can use this method to calculate a view's origin in window space like this:
[aView.superview convertPoint:aView.frame.origin toView:nil];
2014 Edit: Looking at the popularity of Matt__C's comment it seems reasonable to point out that the coordinates...
- don't change when rotating the device.
- always have their origin in the top left corner of the unrotated screen.
- are window coordinates: The coordinate system ist defined by the bounds of the window. The screen's and device coordinate systems are different and should not be mixed up with window coordinates.
Swift 5+:
let globalPoint = aView.superview?.convert(aView.frame.origin, to: nil)
Swift 3, with extension:
extension UIView{
var globalPoint :CGPoint? {
return self.superview?.convert(self.frame.origin, to: nil)
}
var globalFrame :CGRect? {
return self.superview?.convert(self.frame, to: nil)
}
}
In Swift:
let globalPoint = aView.superview?.convertPoint(aView.frame.origin, toView: nil)
Here is a combination of the answer by @Mohsenasm and a comment from @Ghigo adopted to Swift
extension UIView {
var globalFrame: CGRect? {
let rootView = UIApplication.shared.keyWindow?.rootViewController?.view
return self.superview?.convert(self.frame, to: rootView)
}
}