Skip to content

Instantly share code, notes, and snippets.

@JeOam
Last active November 4, 2015 09:22
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JeOam/1a3cba3c0544b5510599 to your computer and use it in GitHub Desktop.
Save JeOam/1a3cba3c0544b5510599 to your computer and use it in GitHub Desktop.
Compatible with iOS 6 and iOS 7: Layout

iOS 7 代码布局适配:坐标起点 iOS 7 中 UIViewController 使用了全屏布局的方式,也就是说导航栏和状态栏都是不占实际空间的,状态栏默认是全透明的,导航栏默认是毛玻璃的透明效果。例如在一个 view 中加入:

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,100,100)];
[label setBackgroundColor:[UIColor greenColor]];
[self.view addSubview:label];

上面代码加在没有 UINavigationController 作为 rootViewController 的情况下,得到的效果是:

有 UINavigationController 作为 rootViewController 的情况下:


如果我们设置导航栏不透明,我们的坐标就会从导航栏下面开始算起,导航栏占用空间位置:

self.navigationController.navigationBar.translucent = NO;

得到的效果如图:

如果我们修改 UIViewController 的属性 edgesForExtendedLayoutUIRectEdgeNone,可以达到坐标就会从导航栏下面开始算起的效果(edgesForExtendedLayout 默认值是 UIRectEdgeAll)

if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]){ // 该属性在 iOS 7 中才可用
    self.edgesForExtendedLayout = UIRectEdgeNone;
}
@JeOam
Copy link
Author

JeOam commented Jul 15, 2014

iOS 7 代码布局适配:UITableView
iOS 7 的初始化位置都是从屏幕开始的,但是如果使用 UITableView 全屏显示,在有导航栏的情况下,你会发现它的位置是正确的。那是因为在 iOS 7 的 UIViewController 中增加了automaticallyAdjustsScrollViewInsets 属性。

automaticallyAdjustsScrollViewInsets:
Default value is YES, which allows the view controller to adjust its scroll view insets in response to the screen areas consumed by the status bar, navigation bar, and toolbar or tab bar. Set to NO if you want to manage scroll view inset adjustments yourself, such as when there is more than one scroll view in the view hierarchy.

加入下面代码后:

self.automaticallyAdjustsScrollViewInsets = NO;

得到的效果:

可以在设置 automaticallyAdjustsScrollViewInsets = NO; 后,再让坐标计算起点设置为导航栏下起:

if([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0)
{
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.automaticallyAdjustsScrollViewInsets = NO;
}

可得到默认的 UITableView 全屏显示效果。

@JeOam
Copy link
Author

JeOam commented Jul 15, 2014

更详细的内容:iOS 7 UI Transition Guide

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment