229

a 的位置UIView显然可以由view.centerorview.frame等​​确定,但这只会返回UIView相对于它的直接超级视图的位置。

我需要确定UIView在整个 320x480 坐标系中的位置。例如,如果它UIViewUITableViewCell窗口中的位置可能会发生巨大变化,而与超级视图无关。

任何想法是否以及如何实现?

干杯:)

4

7 回答 7

361

这是一个简单的:

[aView convertPoint:localPosition toView:nil];

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

[aView.superview convertPoint:aView.frame.origin toView:nil];

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

  1. 旋转设备时不要改变。
  2. 它们的原点始终位于未旋转屏幕的左上角。
  3. 窗口坐标:坐标系是由窗口的边界定义的。屏幕坐标系和设备坐标系不同,不应与窗口坐标混淆。
于 2009-09-23T11:32:34.590 回答
72

斯威夫特 5+

let globalPoint = aView.superview?.convert(aView.frame.origin, to: nil)
于 2017-02-01T19:39:15.350 回答
44

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)
    }
}
于 2017-09-12T06:22:59.690 回答
35

在斯威夫特:

let globalPoint = aView.superview?.convertPoint(aView.frame.origin, toView: nil)
于 2015-12-30T13:41:07.260 回答
24

这是@Mohsenasm 的答案和@Ghigo 对Swift 采用的评论的组合

extension UIView {
    var globalFrame: CGRect? {
        let rootView = UIApplication.shared.keyWindow?.rootViewController?.view
        return self.superview?.convert(self.frame, to: rootView)
    }
}
于 2019-07-05T05:26:44.400 回答
2

对我来说,这段代码效果最好:

private func getCoordinate(_ view: UIView) -> CGPoint {
    var x = view.frame.origin.x
    var y = view.frame.origin.y
    var oldView = view

    while let superView = oldView.superview {
        x += superView.frame.origin.x
        y += superView.frame.origin.y
        if superView.next is UIViewController {
            break //superView is the rootView of a UIViewController
        }
        oldView = superView
    }

    return CGPoint(x: x, y: y)
}
于 2020-08-24T13:33:25.563 回答
0

这对我有用

view.layoutIfNeeded() // this might be necessary depending on when you need to get the frame

guard let keyWindow = UIApplication.shared.windows.first(where: { $0.isKeyWindow }) else { return }

let frame = yourView.convert(yourView.bounds, to: keyWindow)

print("frame: ", frame)
于 2021-11-17T05:25:43.083 回答