Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using convertPoint to get the relative position inside a parent UIView

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 setup:

enter image description here

I want to get the center coordinates of the UIButton relative to the UIView.

In other words, the UIButton center may be 215, 80 within the UITableViewCell, but relative to the UIView they should be more like 260, 165. How do I convert between the two?

Here's what I've tried:

[[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

I could do it the hard way by looping through all of the button's superviews and adding up the x and y coordinates, but I suspect that's overkill. I just need to find the right combination of covertPoint settings. Right?

like image 701
Axeva Avatar asked Apr 08 '13 15:04

Axeva


4 Answers

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+

let p = button.superview!.convert(button.center, to: self.view)

// or

let buttonCenter = CGPoint(x: button.bounds.midX, y: button.bounds.midY)
let p = button.convert(buttonCenter, to: self.view)
like image 148
Martin R Avatar answered Oct 20 '22 14:10

Martin R


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)
like image 20
Trev14 Avatar answered Oct 20 '22 12:10

Trev14


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
like image 14
rsc Avatar answered Oct 20 '22 12:10

rsc


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)
}
like image 10
AamirR Avatar answered Oct 20 '22 13:10

AamirR