從iOS7開始,view controllers默認使用全屏布局(full-screen layout)。同時引進了不少屬性,使你能更自由地控制view controllers如何布局views。這些屬性是:
edgesForExtendedLayout
通過設置此屬性,你可以指定view的邊(上、下、左、右)延伸到整個屏幕。
typedef enum : NSUInteger {
UIRectEdgeNone = 0,
UIRectEdgeTop = 1 << 0,
UIRectEdgeLeft = 1 << 1,
UIRectEdgeBottom = 1 << 2,
UIRectEdgeRight = 1 << 3,
UIRectEdgeAll = UIRectEdgeTop | UIRectEdgeLeft | UIRectEdgeBottom | UIRectEdgeRight
} UIRectEdge;
edgesForExtendedLayout屬性是enum類型UIRectEdge。默認值是UIRectEdgeAll, 意味著view會被拓展到整個屏幕。比如,當你把一個UIViewControllerpush到一個UINavigationController上:
UIViewController *viewController = [[UIViewController alloc] init]; viewController.view.backgroundColor = [UIColor redColor];
UINavigationController *mainNavigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
結果是這樣的:
比你所見,經色背景延伸到了navigation bar和status bar(延伸到整個屏幕)。
接下來,如果你把值設為UIRectEdgeNone, 也就是不讓view延伸到整個屏幕:
UIViewController *viewController = [[UIViewController alloc] init]; viewController.view.backgroundColor = [UIColor redColor];
viewController.edgesForExtendedLayout = UIRectEdgeNone;
UINavigationController *mainNavigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
結果是這樣的:
關于這個屬性,值得一提的是:它只有當viewController被嵌到別的container view controller中時才會起作用
如蘋果官方所言:
This property is applied only to view controllers that are embedded in a container such as UINavigationController. The window’s root view controller does not react to this property. The default value of this property is UIRectEdgeAll.
automaticallyAdjustsScrollViewInsets
當你的view是UIScrollerView或其子(UITableView)時, 這個屬性就派上用場了。你想讓你的table從navigation bar的底部開始(否則navigation bar擋住了table上部分),同時又希望滾動時,table延伸到整個屏幕(behind the navigation bar)。此時若用edgesForExtendedLayout,滾動時無法滿足要求,因為table始終從navigation bar底部開始,滾動時不會behind it。
automaticallyAdjustsScrollViewInsets就能很好地滿足需求,設置些屬性值為YES(也是默認值),viewController會table頂部添加inset,所以table會出現在navigation bar的底部。但是滾動時又能覆蓋整個屏幕:
當設在NO時:
無論是YES or NO,滾支時table都是覆蓋整個屏幕的,但是YES時,table不會被navigation bar擋住。
從蘋果的官方文檔可知,不只是navigation bar,status bar, search bar, navigation bar, toolbar, or tab bar都有類似的效果。
The default value of this property is
YES
, which lets container view controllers know that they should adjust the scroll view insets of this view controller’s view to account for screen areas consumed by a status bar, search bar, navigation bar, toolbar, or tab bar. Set this property toNO
if your view controller implementation manages its own scroll view inset adjustments.
extendedLayoutIncludesOpaqueBars
extendedLayoutIncludesOpaqueBars是前面兩個屬性的補充。如果status bar是不透明的,view不會被延伸到status bar,除非extendedLayoutIncludesOpaqueBars = YES;
如果想要讓你的view延伸到navigation bar(edgesForExtendedLayout to UIRectEdgeAll)并且設置此屬性為NO(默認)。view就不會延伸到不透明的status bar。