Reputation: 9690
I have a few UIButton
instances inside a UIView
, which in turn is inside the main UIView
of the app. What I’m trying to get is a CGRect
of one of the buttons’ frames, relative to the window.
So, for instance, if my inner view is at 50, 50
in relation to the main view, then the button is at 10, 10
inside that, I’d want to return 60, 60
.
Is there an easy way to do that, without having to keep track of parent views and add them up, etc.?
Upvotes: 2
Views: 3210
Reputation: 2306
UIView *parent = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 50, 50)];
UIView *child = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 10, 10)];
[parent addSubview:child];
[self.view addSubview:parent];
NSLog(NSStringFromCGRect([self.view convertRect:child.frame fromView:child.superview]));
Result in log:
{{60, 60}, {10, 10}}
Upvotes: 3
Reputation: 6990
You can convert a rect to a different view's coordinate system using -[UIView convertRect:toView]
and -[UIView convertRect:fromView:]
.
So, if you have a reference to your outermost view (perhaps if you're using a navigation controller, that might be the outmost view):
UIView *outerView = self.navigationController.view;
UIView *innerView = self.myButton;
CGRect buttonRect = [self.view convertRect:self.innerView.frame toView:outerView];
There are also equivalent convertPoint:
methods. It's then really just a case of working out which views you want to convert from / to.
Upvotes: 4
Reputation: 17186
Use below function.
- (CGPoint)convertPoint:(CGPoint)point toView:(UIView *)view;
CGPoint pt = [button convertPoint:CGPointMake(button.frame.origin.x, button.frame.origin.y) toView:yourWindow];
Upvotes: 0