iPhone - 在整个UIWindow中获取UIView的位置

ada*_*dam 202 iphone cocoa-touch uiview uiwindow ios

的位置UIView可以明显受到确定view.centerview.frame等等,但这只是返回的位置UIView相对于它的即时上海华.

我需要确定UIView整个320x480坐标系统的位置.例如,如果UIView是在UITableViewCell窗口内它的位置可以大大irregardless的上海华盈的改变.

任何想法是否以及如何可行?

干杯:)

Nik*_*uhe 331

这很简单:

[aView convertPoint:localPosition toView:nil];
Run Code Online (Sandbox Code Playgroud)

...将局部坐标空间中的点转换为窗口坐标.您可以使用此方法在窗口空间中计算视图的原点,如下所示:

[aView.superview convertPoint:aView.frame.origin toView:nil];
Run Code Online (Sandbox Code Playgroud)

2014编辑:看看Matt__C评论的受欢迎程度,似乎有理由指出坐标......

  1. 旋转设备时不要改变.
  2. 它们的起源始终位于未旋转屏幕的左上角.
  3. 窗口坐标:坐标系由窗口的边界定义.屏幕和设备坐标系不同,不应与窗口坐标混淆.

  • 请注意,在toView参数中指定nil会为您提供设备坐标,如果您不是纵向,则不会是您想要的设备坐标.请参阅[convertpointtoview-in-landscape-mode-giving-wrong-values](http://stackoverflow.com/questions/6452716/convertpointtoview-in-landscape-mode-giving-wrong-values) (40认同)
  • 将@Matt__C链接解决方案适用于您的案例,它将变为:`[view.superview convertPoint:view.frame.origin toView:[UIApplication sharedApplication] .keyWindow.rootViewController.view]` (17认同)
  • 如果您的superView没有superView,则根本不应该看到您的视图 (3认同)
  • 这个方法一直为我返回`aView.frame.origin`。我费了些力气才意识到自己观点的超级观点本身并没有超级观点。 (2认同)
  • 8年后,我想对此表示感谢! (2认同)

Yuc*_*ong 44

斯威夫特4:

let globalPoint = aView.superview?.convert(aView.frame.origin, to: nil)
Run Code Online (Sandbox Code Playgroud)


Shl*_*rtz 28

在Swift中:

let globalPoint = aView.superview?.convertPoint(aView.frame.origin, toView: nil)
Run Code Online (Sandbox Code Playgroud)


Moh*_*asm 26

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)
    }
}
Run Code Online (Sandbox Code Playgroud)


Vla*_*eys 19

这是@Mohsenasm 的答案和@Ghigo 对 Swift 采纳的评论的结合

extension UIView {
    var globalFrame: CGRect? {
        let rootView = UIApplication.shared.keyWindow?.rootViewController?.view
        return self.superview?.convert(self.frame, to: rootView)
    }
}
Run Code Online (Sandbox Code Playgroud)