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

问题描述 投票:0回答:8

UIView
的位置显然可以由
view.center
view.frame
等确定。但这仅返回
UIView
相对于其直接超级视图的位置。

我需要确定

UIView
在整个320x480坐标系中的位置。例如,如果
UIView
位于
UITableViewCell
中,则无论超级视图如何,它在窗口内的位置都可能发生巨大变化。

有什么想法可以实现吗?

iphone cocoa-touch ios uiview uiwindow
8个回答
365
投票

这很简单:

[aView convertPoint:localPosition toView:nil];

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

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

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

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

78
投票

斯威夫特 5+:

let globalPoint = aView.superview?.convert(aView.frame.origin, to: nil)

46
投票

使用扩展:

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)
    }
}

36
投票

在斯威夫特:

let globalPoint = aView.superview?.convertPoint(aView.frame.origin, toView: nil)

28
投票

这是 @Mohsenasm 的答案和@Ghigo 的评论的组合,被采纳到 Swift

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

4
投票

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

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)
}

4
投票

对我来说效果很好:)

extension UIView {
    var globalFrame: CGRect {
        return convert(bounds, to: window)
    }
}

1
投票

这对我有用

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)
© www.soinside.com 2019 - 2024. All rights reserved.