我已经看了十几个关于这个主题的SO问题,但没有一个答案对我有用。也许这会帮助我回到正确的道路上。
想象一下这个设置:
我想得到UIButton相对于UIView的center
坐标。
换句话说,UIButton中心在UITableViewCell中可能是215,80,但相对于UIView,它们应该更像260,165。如何在两者之间进行转换?
这是我尝试过的:
[[self.view superview] convertPoint:button.center fromView:button]; // fail
[button convertPoint:button.center toView:self.view]; // fail
[button convertPoint:button.center toView:nil]; // fail
[button convertPoint:button.center toView:[[UIApplication sharedApplication] keyWindow]]; // fail
我可以通过循环遍历所有按钮的超级视图并添加x和y坐标来做到这一点,但我怀疑这有点过分。我只需要找到covertPoint设置的正确组合。对?
button.center
是其superview坐标系中指定的中心,所以我假设以下工作:
CGPoint p = [button.superview convertPoint:button.center toView:self.view]
或者您在自己的坐标系中计算按钮的中心并使用:
CGPoint buttonCenter = CGPointMake(button.bounds.origin.x + button.bounds.size.width/2,
button.bounds.origin.y + button.bounds.size.height/2);
CGPoint p = [button convertPoint:buttonCenter toView:self.view];
斯威夫特4
var p = button.convert(button.center, to: self.view)
马丁答案是对的。对于使用Swift的开发人员,您可以使用以下方法获取相对于屏幕的对象(按钮,视图......)的位置:
var p = obj.convertPoint(obj.center, toView: self.view)
println(p.x) // this prints the x coordinate of 'obj' relative to the screen
println(p.y) // this prints the y coordinate of 'obj' relative to the screen
斯威夫特4
你需要从按钮调用convert
,而不是superview。在我的情况下,我需要宽度数据,所以我转换边界而不是中心点。以下代码适用于我:
let buttonAbsoluteFrame = button.convert(button.bounds, to: self.view)
这是@ Pablo的答案的Swift 3更新,在我的案例中当然很有用。
if let window = UIApplication.shared.keyWindow {
parent.convert(child.frame.origin, to: window)
}
在swift 2.2中为我工作:
var OrignTxtNomeCliente:CGPoint!
if let orign = TXT_NomeCliente.superview, let win = UIApplication.sharedApplication().keyWindow {
OrignTxtNomeCliente = orign.convertPoint(TXT_NomeCliente.frame.origin, toView: win)
}