在很多时候,我们需要去计算一个UIView相对屏幕的坐标,来实现一些UI效果。
在这个UIView未被嵌套多层的时候,相对屏幕的坐标很好算,只需要精准的拿到每层superview变量去计算。
但是很多情况下,我们的UIView可能嵌套了很多层(我在项目中遇到的相对Controller.view就有6层之多),并且被嵌套在UIScrollView或者UITableView中,这个时候不可能去拿到每一层嵌套的superview的变量去计算。
基于这个需求,我写了一个通用的方法,可以很方便的拿到任意一个UIView相对屏幕的坐标。
代码虽然很简单,但是还是蛮实用的。
- /**
- * 计算一个view相对于屏幕(去除顶部statusbar的20像素)的坐标
- * iOS7下UIViewController.view是默认全屏的,要把这20像素考虑进去
- */
- + (CGRect)relativeFrameForScreenWithView:(UIView *)v
- {
- BOOL iOS7 = [[[UIDevice currentDevice] systemVersion] floatValue] >= 7;
- CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
- if (!iOS7) {
- screenHeight -= 20;
- }
- UIView *view = v;
- CGFloat x = .0;
- CGFloat y = .0;
- while (view.frame.size.width != 320 || view.frame.size.height != screenHeight) {
- x += view.frame.origin.x;
- y += view.frame.origin.y;
- view = view.superview;
- if ([view isKindOfClass:[UIScrollView class]]) {
- x -= ((UIScrollView *) view).contentOffset.x;
- y -= ((UIScrollView *) view).contentOffset.y;
- }
- }
- return CGRectMake(x, y, v.frame.size.width, v.frame.size.height);
- }
获取view相对于屏幕的坐标。有方法的:
- CGRect frame = [view convertRect:view.bounds toView:nil];