http://stackoverflow.com/questions/15883305/using-convertpoint-to-get-the-relative-position-inside-a-parent-uiview
12
favorite4
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]]; // failI 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?
ios objective-cshareimprove this questionasked Apr 8 '13 at 15:37
Axeva1,71511543
It will help if you add the following to your question: The frames of all 4 views in your image, the output you get from the methods you have tried, and the value you actually want. –
rmaddy Apr 8 '13 at 15:43
2 Answers
activeoldestvotes26accepted
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];
shareimprove this answeredited Apr 8 '13 at 15:51answered Apr 8 '13 at 15:45
Martin R188k15286364
1
Bingo! Your first attempt was what I was looking for. The center being tied to the coordinate system of the superview is what I was missing. Thank you! –
Axeva Apr 8 '13 at 16:10
4
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 screenprintln(p.y) // this prints the y coordinate of 'obj' relative to the screen
shareimprove this answeredited Jul 27 at 3:59answered Nov 19 '14 at 7:01
RSC1,732812
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。