john
john

Reputation: 3103

iOS: UIView's origin with respect to UIWindow

A UIView has an origin contained in its frame or bounds properties with respect to its superview. Say I want to do something which grabs the origin of a UIView with respect to the UIWindow instead. Do I have to go each step up the hierarchy in order to make this calculation or is there a simpler, more direct way?

Upvotes: 1

Views: 1495

Answers (3)

Hector Matos
Hector Matos

Reputation: 1056

The best and easiest way to do this is by using convertPoint:toView or convertRect:toView on UIWindow. In order to do this correctly, you need to supply a view whose window matches the window of the view whose coordinates you are trying to convert.

For your question, you need to know a view's origin with respect to its location in the window. Thankfully, you don't need to know the window in order to get this. According to the documentation of UIView's convert:to methods.

The view into whose coordinate system point is to be converted. If view is nil, this method instead converts to window base coordinates. Otherwise, both view and the receiver must belong to the same UIWindow object.

This means that you can just supply nil to achieve what you need!

In Swift:

let pointInWindow = yourView.convert(.zero, to: nil)

In Objective-C:

CGPoint pointInWindow = [yourView convertPoint:CGPointZero toView:nil];

Upvotes: 0

Jim
Jim

Reputation: 5960

to find out where a view aView is in the application window, try

[aView convertRect:aView.frame toView:[UIWindow screen]]

This method is in the UIView Class Reference

Upvotes: 2

beryllium
beryllium

Reputation: 29767

I guess you looking for this method

convertPoint:toView

Upvotes: 5

Related Questions