Using convertPoint to get the relative position inside a parent UIView

后端 未结 5 1425
臣服心动
臣服心动 2020-12-07 13:12

I\'ve looked at a dozen SO questions on this topic, and none of the answers have worked for me. Maybe this will help get me back on the right path.

Imagine this set

相关标签:
5条回答
  • 2020-12-07 13:41

    in swift 2.2 worked for me:

    var OrignTxtNomeCliente:CGPoint!
    
    if let orign = TXT_NomeCliente.superview, let win = UIApplication.sharedApplication().keyWindow {
            OrignTxtNomeCliente = orign.convertPoint(TXT_NomeCliente.frame.origin, toView: win)
        }
    
    0 讨论(0)
  • 2020-12-07 13:46

    Here is Swift 3 update of @Pablo's answer, which off course worked great in my case.

    if let window = UIApplication.shared.keyWindow {
        parent.convert(child.frame.origin, to: window)
    }
    
    0 讨论(0)
  • 2020-12-07 13:50

    button.center is the center specified within the coordinate system of its superview, so I assume that the following works:

    CGPoint p = [button.superview convertPoint:button.center toView:self.view]
    

    Or you compute the button's center in its own coordinate system and use that:

    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)
    
    0 讨论(0)
  • 2020-12-07 13:56

    Swift 5.2

    You need to call convert from the button, not the superview. In my case I needed width data so I converted the bounds instead of just center point. The code below works for me:

    let buttonAbsoluteFrame = button.convert(button.bounds, to: self.view)
    
    0 讨论(0)
  • 2020-12-07 13:57

    Martin answer is correct. For developers using Swift, you can get the position of an object (button, view,...) relative to the screen by using:

    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
    
    0 讨论(0)
提交回复
热议问题