UIView
的位置显然可以由 view.center
或 view.frame
等确定。但这仅返回 UIView
相对于其直接超级视图的位置。
我需要确定
UIView
在整个320x480坐标系中的位置。例如,如果 UIView
位于 UITableViewCell
中,则无论超级视图如何,它在窗口内的位置都可能发生巨大变化。
有什么想法可以实现吗?
这很简单:
[aView convertPoint:localPosition toView:nil];
...将局部坐标空间中的点转换为窗口坐标。您可以使用此方法来计算窗口空间中视图的原点,如下所示:
[aView.superview convertPoint:aView.frame.origin toView:nil];
2014 年编辑: 看看 Matt__C 评论的受欢迎程度,指出坐标似乎是合理的......
斯威夫特 5+:
let globalPoint = aView.superview?.convert(aView.frame.origin, to: nil)
使用扩展:
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)
}
}
在斯威夫特:
let globalPoint = aView.superview?.convertPoint(aView.frame.origin, toView: 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)
}
对我来说效果很好:)
extension UIView {
var globalFrame: CGRect {
return convert(bounds, to: window)
}
}
这对我有用
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)