iOS开发 ☞ 关于带系统导航栏坐标的问题

原文链接:http://blog.csdn.net/magiczyj/article/details/50680242 
在实际编程中,特别是iOS7以后,当我们使用系统自带的UINavigationController时,很容易弄不清楚此时的变成原点在哪里,下面详细的说一下。 
如果你的导航栏设置了背景图片,我猜想苹果默认会帮你布局,也就是说编程的原点在导航栏下面的左上角。

效果如下: 

这里写图片描述

下面是代码:

//首先在AppDelegate里面
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    root = [[RootViewController alloc] init];
    UINavigationController *rootNvc = [[UINavigationController alloc] initWithRootViewController:root];
    [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"1"] forBarMetrics:UIBarMetricsDefault];
 //方法二
 //    [rootNvc.navigationBar setBackgroundImage:[UIImage imageNamed:@"1"] forBarMetrics:UIBarMetricsDefault];
    self.window.rootViewController = rootNvc;
    [self.window makeKeyAndVisible];
    return YES;
}
//其次在视图控制器中
- (void)viewDidLoad {
    [super viewDidLoad];
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
    view.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:view];
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

结论:如果导航栏设置了背景图片,那么编程原点就在导航栏的下面。

在iOS 7中,苹果引入了一个新的属性,叫做[UIViewController setEdgesForExtendedLayout:],它的默认值为UIRectEdgeAll。当你的容器是navigation controller时,默认的布局将从navigation bar的顶部开始。这就是为什么所有的UI元素都往上漂移了44pt。 
如果没有设置背景图片也想有同样的效果,需要在控制器中添加如下代码:

   if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.f) {
       self.edgesForExtendedLayout = UIRectEdgeNone;
   }
  • 1
  • 2
  • 3

综上,如果想要编程的原点在导航栏下,不妨在BaseViewController中添加上面这句话。

因为iOS7鼓励全屏布局,它的默认值很自然地是UIRectEdgeAll,四周边缘均延伸,就是说,如果即使视图中上有navigationBar,下有tabBar,那么视图仍会延伸覆盖到四周的区域,但是如果导航控制器拥有背景图片(并且透明度为1),视图自然不能延伸到最顶部。

猜你喜欢

转载自blog.csdn.net/u012891546/article/details/78135977