Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
548 views
in Technique[技术] by (71.8m points)

ios - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...