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

时间:2013-04-08 15:37:18

标签: ios objective-c

我已经看了十几个关于这个主题的SO问题,但没有一个答案对我有用。也许这会让我回到正确的道路上。

想象一下这个设置:

enter image description here

我想得到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设置的正确组合。正确?

4 个答案:

答案 0 :(得分:106)

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];

Swift 4

var p = button.convert(button.center, to: self.view)

答案 1 :(得分:11)

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

答案 2 :(得分:6)

以下是@ Pablo回答的 Swift 3 更新,这在我的案例中当然很有效。

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

答案 3 :(得分: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)
    }