문제

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

도움이 되었습니까?

해결책 2

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

다른 팁

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.

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];
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top