今天看啥  ›  专栏  ›  Adrenine

布局之extendedLayout与sizeToFit

Adrenine  · 掘金  ·  · 2017-12-13 08:46

iOS 7以后在ViewController里面引进了一系列属性用于管理页面布局。 extendedLayout有几个相似的参数:

edgesForExtendedLayout
automaticallyAdjustsScrollViewInsets
extendedLayoutIncludesOpaqueBars

下面是Apple官方提供的文档解释,看过之后还是觉得太过于抽象,于是用代码来实验吧。 **edgesForExtendedLayout ** The extended edges to use for the layout. **automaticallyAdjustsScrollViewInsets ** A Boolean value that indicates whether the view controller should automatically adjust its scroll view insets. **extendedLayoutIncludesOpaqueBars ** A Boolean value indicating whether or not the extended layout includes opaque bars.
edgesForExtendedLayout 新建单个页面的项目,然后加上UINavigationController

把背景设置成红色,界面效果如下:
所以可以看到在iOS7后,View的布局是默认全屏的,Navigation Bar默认是半透明的,于是在Navigation Bar下面可以看到红色的背景。

- (void)viewDidLoad {  
  [super viewDidLoad]; 
  self.edgesForExtendedLayout = UIRectEdgeNone;
}

将edgesForExtendedLayout设置成UIRectEdgeNone,表明View是不要扩展到整个屏幕的。页面效果如下:

 UIRectEdge是个枚举类型,其他的值通过字面意思也是非常容易理解的。

typedef enum : NSUInteger { 
  UIRectEdgeNone = 0, 
  UIRectEdgeTop = 1 << 0, 
  UIRectEdgeLeft = 1 << 1, 
  UIRectEdgeBottom = 1 << 2, 
  UIRectEdgeRight = 1 << 3, 
  UIRectEdgeAll = UIRectEdgeTop | UIRectEdgeLeft | UIRectEdgeBottom | UIRectEdgeRight} UIRectEdge;

**automaticallyAdjustsScrollViewInsets ** 这个属性用于如果页面是ScrollView或者UITableView,通常我们希望ScrollView或者UITableView内容显示是在UINavigation Bar下面。通过设置edgesForExtendedLayout = UIRectEdgeNone或者self.navigationController.navigationBar.translucent =NO;可以让view的布局从UINavigation Bar下面开始,不过一个副作用就是当页面滑动的时候,view是没有办法占据全屏的。automaticallyAdjustsScrollViewInsets就可以很好的完成这个需求。self.automaticallyAdjustsScrollViewInsets = NO;

这时UITableView会被UINavigation Bar遮挡住。self.automaticallyAdjustsScrollViewInsets = YES;
这时可以看到UITableView的内容会从UINavigation Bar下面开始,并且这个页面的View还是占据整个屏幕的,所以这一个属性完全搞定! extendedLayoutIncludesOpaqueBars 如果状态栏是不透明的,那么页面的布局默认是不会包含状态栏的,除非将这个属性设置成为YES。所以如果你的页面扩展到Navigation Bar (edgesForExtendedLayout=UIRectEdgeAll),要是这个属性设置成NO (default), 如果状态栏是不透明的话,页面是不会扩展到状态栏的。 在这篇文章http://redth.codes/ios7-full-screen-layout/ 里面提到有些时候automaticallyAdjustsScrollViewInsets并不能帮助我们正常计算ScrollView/TableView的Inset,这时候就自己设置咯。 self.myTableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);


UIView的sizeToFit:和fitSize方法文档说明:

- (CGSize)sizeThatFits:(CGSize)size; // return 'best' size to fit given size. does not actually resize view. Default is return existing view size
- (void)sizeToFit; // calls sizeThatFits: with current view bounds and changes bounds size.
  • (CGSize)sizeThatFits:(CGSize)size 让View计算并返回subView最适合的大小
  • sizeToFit 调整大小和移动使其子视图处于最佳位置

参考文章: http://stackoverflow.com/questions/18798792/explaining-difference-between-automaticallyadjustsscrollviewinsets-extendedlayo http://redth.codes/ios7-full-screen-layout/




原文地址:访问原文地址
快照地址: 访问文章快照