简体   繁体   English

iOS:UIView关于UIWindow的起源

[英]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. UIView在其框架或bounds属性中包含关于其超级视图的原点。 Say I want to do something which grabs the origin of a UIView with respect to the UIWindow instead. 说我想做一些事情来代替UIWindow来获取UIView的起源。 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 convertPoint:toView

to find out where a view aView is in the application window, try 要找出视图aView在应用程序窗口中的位置,请尝试

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

This method is in the UIView Class Reference 此方法在UIView类参考中

The best and easiest way to do this is by using convertPoint:toView or convertRect:toView on UIWindow . 最好和最简单的方法是在UIWindow上使用convertPoint:toViewconvertRect:toView 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. 根据UIViewconvert:to方法的文档。

The view into whose coordinate system point is to be converted. 坐标系点要转换成的视图。 If view is nil, this method instead converts to window base coordinates. 如果view为nil,则此方法将转换为窗口基础坐标。 Otherwise, both view and the receiver must belong to the same UIWindow object. 否则,视图和接收者都必须属于同一个UIWindow对象。

This means that you can just supply nil to achieve what you need! 这意味着您只需提供nil可以实现您所需要的!

In Swift: 在Swift中:

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

In Objective-C: 在Objective-C中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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