UIView的位置显然可以由view决定。center或view。frame等等,但这只返回UIView相对于它的直接父视图的位置。

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

你有什么想法吗?


当前回答

斯威夫特5 +:

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

其他回答

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

以下是@Mohsenasm的回答和@Ghigo对Swift的评论

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

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

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

这对我很有效

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)

斯威夫特5 +:

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