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

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

你有什么想法吗?


当前回答

迅速:

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

其他回答

这对我很有效

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)

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

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

斯威夫特5 +:

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

对我来说很有用:)

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

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