简体   繁体   中英

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?

I guess you looking for this method

convertPoint:toView

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

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM