使用convertPoint获取父UIView内的相对位置


68

我已经查看了关于该主题的十几个SO问题,但没有一个答案对我有用。也许这将帮助我重新走上正确的道路。

想象一下这个设置:

在此处输入图片说明

我想获取center相对于UIView的UIButton的坐标。

换句话说,UIButtonViewCell中的UIButton中心可能是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设置的正确组合即可。对?


如果将以下内容添加到问题中,将有所帮助:图像中所有4个视图的框架,尝试使用的方法获得的输出以及实际需要的值。
rmaddy13年

Answers:


131

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)

3
答对了!您的第一次尝试是我想要的。我所缺少的是与超级视图的坐标系绑定的中心。谢谢!
Axeva

谢谢@Martin R。这很有帮助
Chamath Jeevan

1
斯威夫特3: var buttonCenter = CGPoint(x: button.bounds.origin.x + button.bounds.size.width / 2, y: button.bounds.origin.y + button.bounds.size.height / 2) var p = button.convertPoint(buttonCenter, to: self.view)
马特·巴特勒

14

马丁的回答是正确的。对于使用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

1
@Axeva还有一个convertRect更精确的计算在这里
Juan Boero

13

Swift 5.2

您需要convert从按钮调用,而不是从父视图调用。在我的情况下,我需要宽度数据,所以我转换了边界,而不仅仅是中心点。以下代码对我有用:

let buttonAbsoluteFrame = button.convert(button.bounds, to: self.view)

命名框架令人困惑,因为边界的frame.origin为零。如果您只能通过button.bounds获取宽度,为什么要调用convert。如果您确实需要获取视图的相对坐标,请使用convert(button.frame ....)
Almas Adilbek,

9

这是@Pablo答案的Swift 3更新,在我看来,这当然很有效。

if let window = UIApplication.shared.keyWindow {
    parent.convert(child.frame.origin, to: window)
}

1

在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)
    }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.