Search code examples
iosobjective-cuiviewboundscgrect

Get a UIView’s bounds relative to the window?


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


Solution

  • 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}}