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:
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?
Solution 1:
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)
Solution 2:
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)