a 的位置UIView
显然可以由view.center
orview.frame
等确定,但这只会返回UIView
相对于它的直接超级视图的位置。
我需要确定UIView
在整个 320x480 坐标系中的位置。例如,如果它UIView
在UITableViewCell
窗口中的位置可能会发生巨大变化,而与超级视图无关。
任何想法是否以及如何实现?
干杯:)
a 的位置UIView
显然可以由view.center
orview.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)
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)
}
}
在斯威夫特:
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)
}
这对我有用
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)