ios iPhone - 在整个 UIWindow 中获取 UIView 的位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1465394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iPhone - Get Position of UIView within entire UIWindow
提问by adam
The position of a UIView
can obviously be determined by view.center
or view.frame
etc. but this only returns the position of the UIView
in relation to it's immediate superview.
a 的位置UIView
显然可以由view.center
或view.frame
等确定,但这只会返回与UIView
它的直接上级视图相关的位置。
I need to determine the position of the UIView
in the entire 320x480 co-ordinate system. For example, if the UIView
is in a UITableViewCell
it's position within the window could change dramatically irregardless of the superview.
我需要确定UIView
整个 320x480 坐标系中的位置。例如,如果UIView
是在UITableViewCell
窗口内它的位置可能会改变大大irregardless的上海华盈的。
Any ideas if and how this is possible?
任何想法是否以及如何可能?
Cheers :)
干杯:)
回答by Nikolai Ruhe
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...
2014 年编辑:看看 Matt__C 评论的流行程度,指出坐标......
- 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.
- 旋转设备时不要改变。
- 它们的原点始终位于未旋转屏幕的左上角。
- 是窗口坐标:坐标系由窗口的边界定义。屏幕和设备坐标系不同,不应与窗口坐标混淆。
回答by Yuchen Zhong
Swift 5, Swift 4:
斯威夫特 5、斯威夫特 4:
let globalPoint = aView.superview?.convert(aView.frame.origin, to: nil)
回答by Mohsenasm
Swift 3, with extension:
Swift 3,带扩展名:
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)
}
}
回答by Shlomi Schwartz
In Swift:
在斯威夫特:
let globalPoint = aView.superview?.convertPoint(aView.frame.origin, toView: nil)
回答by Vlad Spreys
Here is a combination of the answer by @Mohsenasm and a comment from @Chigo adopted to Swift
这是@Mohsenasm 的回答和@Chigo 对 Swift 采纳的评论的结合
extension UIView {
var globalFrame: CGRect? {
let rootView = UIApplication.shared.keyWindow?.rootViewController?.view
return self.superview?.convert(self.frame, to: rootView)
}
}