iOS development-layoutguide (from Top/bottom layoutguide to safe area)

Source: Internet
Author: User

IOS7 Toplayoutguide/bottomlayoutguide

To create a project called Layoutguidestudy, let's open a look at Main.storyboard:



Storyboard-top_bottom_layoutguide.png

You can see the two things that appear under the View controller Toplayoutguide/bottomlayoutguide, and are at the same level as the controller's view.
And in the Uiviewcontroller header file, these two attributes are the ID type that follows a Uilayoutsupport protocol and is read-only property:

// These objects may be used as layout items in the NSLayoutConstraint API@property(nonatomic,readonly,strong) id<UILayoutSupport> topLayoutGuide NS_AVAILABLE_IOS(7_0);@property(nonatomic,readonly,strong) id<UILayoutSupport> bottomLayoutGuide NS_AVAILABLE_IOS(7_0);

This shows that the two layoutguide are automatically created and managed by the system, which also explains why Main.storyboard automatically appears toplayoutguide/bottomlayoutguide in the project we created just now.

Look what it's for.

We drag a red view into the controller's view, add constraints, notice is the lower right corner of the constraint setting box, about the top constraints of the base view drop-down selection, Xcode by default check the top Layout guide:



Autolayout-uselayoutguide.png

, add the width and height constraints, and finally constrain the result:



Constraint_result.png
Direct build looks at the result:

Run-result.png

You can see that the top constraint is based on the toplayoutguide provided by the system, and the system automatically avoids the upper status bar for this view.
We print a red view inside the Viewcontroller:

<UIView: 0x7ff10860fa90; frame = (0 20; 240 128); autoresize = RM+BM; layer = <CALayer: 0x60000003b5c0>>

The Y value of the red view is 20. Exactly the height of the status bar. Thus, the role of top layout guide is to help developers isolate the space in the status bar when automating layout. So let's look at the situation of the navigation controller (the navigation bar at the top):



Navagation-result.png

Build to see the results:



Run_nav_result.png
The Top Layout Guide also automatically helps isolate the status bar + navigation bar.
Print a yellow view inside the Viewcontroller:
<UIView: 0x7fb04fe08040; frame = (0 64; 240 128); autoresize = RM+BM; layer = <CALayer: 0x61800003ef60>>

The Y value of the yellow view is 64. Just the height of the status bar + navigation bar.

Similarly, Bottomlayoutguide is the Tabbar used to isolate the bottom of the Tabbarcontroller:



Tabbar-bottomguide.png Grilled Toplayoutguide/bottomlayoutguide object:

Viewdidlayoutsubviews method Printing in Uiviewcontroller

- (void)viewDidLayoutSubviews {    [super viewDidLayoutSubviews];    NSLog(@"topLayoutGuide-%@",self.topLayoutGuide);    NSLog(@"bottomLayoutGuide-%@",self.bottomLayoutGuide);}打印结果:topLayoutGuide-<_UILayoutGuide: 0x7fd7cce0c350; frame = (0 0; 0 64); hidden = YES; layer = <CALayer: 0x61000003f2c0>>bottomLayoutGuide-<_UILayoutGuide: 0x7fd7cce0d6b0; frame = (0 667; 0 0); hidden = YES; layer = <CALayer: 0x610000221620>>

This is a _uilayoutguide type of private object, it looks like there is a Frame,hidden,layer property, it feels very similar to UIView ah, then we will verify:

if ([self.topLayoutGuide isKindOfClass:[UIView class]]) {    NSLog(@"topLayoutGuide is an UIView");} if ([self.bottomLayoutGuide isKindOfClass:[UIView class]]) {    NSLog(@"bottomLayoutGuide is an UIView");}打印结果:topLayoutGuide is an UIViewbottomLayoutGuide is an UIView

The conclusion is that Toplayoutguide/bottomlayoutguide is actually an object of the UIView type.
Let's print out the subviews of the Uiviewcontroller view:

- (void)viewDidLayoutSubviews {    [super viewDidLayoutSubviews];     NSLog(@"viewController view subViews %@",self.view.subviews);}打印结果:viewController view subViews (    "<UIView: 0x7ffc774035b0; frame = (0 64; 240 128); autoresize = RM+BM; layer = <CALayer: 0x60800002c720>>",    "<_UILayoutGuide: 0x7ffc7740ae10; frame = (0 0; 0 64); hidden = YES; layer = <CALayer: 0x60800002c480>>",    "<_UILayoutGuide: 0x7ffc7740b1e0; frame = (0 667; 0 0); hidden = YES; layer = <CALayer: 0x60800002b820>>")

This is clear!
To summarize:
Toplayoutguide/bottomlayoutguide is actually a virtual pit view that helps developers avoid the top status bar, navigation bar, and tabbar at the bottom when auto-layout .

IOS9 Uilayoutguide

IOS9, Apple has added a new Uilayoutguide class to see Apple's official explanation for it:

The UILayoutGuide class defines a rectangular area that can interact with Auto Layout. Use layout guides to replace the dummy views you may have created to representinter-view spaces or encapsulation in your user interface

It probably means that uilayoutguide is used to provide a rectangular area that can be used to customize some of the constraint features using auto layout as a virtual view.
I think the Apple engineers think that the previous toplayoutguide/bottomlayoutguide provide virtual Occupy pit view, the isolation navigation bar/tabber idea is good, and then has the inspiration, can make the whole layoutguide become more flexible, Let the developer be able to customize freely, so this uilayoutguide class is designed to come out.

So how to freely customize a uilayoutguide, let's look at several properties of this class:

@property(readonly, strong) NSLayoutXAxisAnchor *leadingAnchor;@property(readonly, strong) NSLayoutXAxisAnchor *trailingAnchor;@property(readonly, strong) NSLayoutXAxisAnchor *leftAnchor;@property(readonly, strong) NSLayoutXAxisAnchor *rightAnchor;@property(readonly, strong) NSLayoutYAxisAnchor *topAnchor;@property(readonly, strong) NSLayoutYAxisAnchor *bottomAnchor;@property(readonly, strong) NSLayoutDimension *widthAnchor;@property(readonly, strong) NSLayoutDimension *heightAnchor;@property(readonly, strong) NSLayoutXAxisAnchor *centerXAnchor;@property(readonly, strong) NSLayoutYAxisAnchor *centerYAnchor;

Nslayoutxaxisanchor,nslayoutyaxisanchor,nslayoutdimension These classes are also following uilayoutguide in
IOS9 after the new, even if very unfamiliar, but we look at the above uilayoutguide several properties inside Leading,trailing,top,bottom,center and other familiar words, You can see that these attributes are used to add layout constraints to the Uilayoutguide object.

We're looking at a new category in UIView:

@interface UIView (uiviewlayoutconstraintcreation) @property (readonly, strong) Nslayoutxaxisanchor *leadinganchor Ns_ Available_ios (9_0); @property (ReadOnly, strong) Nslayoutxaxisanchor *trailinganchor Ns_available_ios (9_0); @property (ReadOnly, Strong) Nslayoutxaxisanchor *leftanchor Ns_available_ios (9_0); @property (ReadOnly, strong) Nslayoutxaxisanchor *rightanchor Ns_available_ios (9_0); @property (ReadOnly, strong) Nslayoutyaxisanchor *topanchor Ns_available_ios (9_0); @property ( ReadOnly, Strong) Nslayoutyaxisanchor *bottomanchor Ns_available_ios (9_0); @property (ReadOnly, Strong) Nslayoutdimension *widthanchor Ns_available_ios (9_0); @property (ReadOnly, strong) Nslayoutdimension *heightanchor NS_ Available_ios (9_0); @property (ReadOnly, strong) Nslayoutxaxisanchor *centerxanchor Ns_available_ios (9_0); @property ( ReadOnly, Strong) Nslayoutyaxisanchor *centeryanchor Ns_available_ios (9_0); @property (ReadOnly, Strong) Nslayoutyaxisanchor *firstbaselineanchor Ns_available_ios (9_0); @property (ReadOnly, Strong) Nslayoutyaxisanchor *lastbaselineanchor Ns_available_ios (9_0); @end 

It's the same as Uilayoutguide. Provides consistent properties. This shows that uilayoutguide can interact with the UIView for auto layout constraints.

We use an example to illustrate:

Create a uilayoutguide, constrain it from the top of the controller view 64, left 0, Width 250, high, so the code inside the Viewdidload method:

// 创建UILayoutGuide *layoutGuide = [[UILayoutGuide alloc] init];// 需要使用UIView的addLayoutGuide方法添加新建的layoutGuide[self.view addLayoutGuide:layoutGuide];// 正式的约束代码[layoutGuide.topAnchor constraintEqualToAnchor:self.view.topAnchor constant:64].active = YES;[layoutGuide.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor].active = YES;[layoutGuide.widthAnchor constraintEqualToConstant:250].active = YES;[layoutGuide.heightAnchor constraintEqualToConstant:200].active = YES;

This makes the constraint code significantly more concise than using Nslayoutconstraint.

Next, we create a purple view, based on this created layoutguide constraints, the top of the purple View distance above the LayoutGuide bottom 20, and layoutguide left alignment, width and height and layoutguide consistent :

UIView *viewBaseLayoutGuide = [[UIView alloc] init];viewBaseLayoutGuide.translatesAutoresizingMaskIntoConstraints = NO;viewBaseLayoutGuide.backgroundColor = [UIColor purpleColor];[self.view addSubview:viewBaseLayoutGuide];[viewBaseLayoutGuide.topAnchor constraintEqualToAnchor:layoutGuide.bottomAnchor constant:20].active = YES;[viewBaseLayoutGuide.leadingAnchor constraintEqualToAnchor:layoutGuide.leadingAnchor].active = YES;[viewBaseLayoutGuide.widthAnchor constraintEqualToAnchor:layoutGuide.widthAnchor].active = YES;[viewBaseLayoutGuide.heightAnchor constraintEqualToAnchor:layoutGuide.heightAnchor].active = YES;

Results of running the program:



LAYOUTGUIDE-TEST.PNGIOS11 Safe Area/safearealayoutguide

IOS11 introduced the concept of a safe area (security Zone), and Apple recommends placing UI controls within this secure area. The scope of this security area is actually the entire screen isolated out of the status bar, the navigation bar, the Tabar, and the range of the iphone x top Fringe, the bottom virtual home gesture Area .
From this introduction can be seen, the so-called safe area is actually upgraded version of the Toplayoutguide/bottomlayoutguide, previously can only limit the layout of Top/bottom, now more powerful.
Take a look at the Uiviewcontroller header file: (Open with Xcode9 or later):

@property(nonatomic,readonly,strong) id<UILayoutSupport> topLayoutGuide API_DEPRECATED_WITH_REPLACEMENT("-[UIView safeAreaLayoutGuide]", ios(7.0,11.0), tvos(7.0,11.0));@property(nonatomic,readonly,strong) id<UILayoutSupport> bottomLayoutGuide API_DEPRECATED_WITH_REPLACEMENT("-[UIView safeAreaLayoutGuide]", ios(7.0,11.0), tvos(7.0,11.0));

Apple tip toplayoutguide/bottomlayoutguide These two properties have expired in iOS11, it is recommended to use the Safearealayoutguide property of UIView (Safearealayoutguide will be introduced later).

In addition, when creating a project with Xcode9 or above, Main.storyboard will default to the Use safe area Layout Guides, and the safe area will appear under Controller view:


Xcode9_safearea.png verify the effect of using Safearea:

As shown, we constrain the red view based on the Safearea area of the controller view provided by storyboard: top distance
Security Zone 0, left side safe area 0, Width 240, height 180:


Constraint-safearea.png
Run the results on iphone 8:

Run-safearea.png

In order to verify the isolation of the safe area at the bottom of the vertical screen iphone x, a brown view is added: The left is safe zone 0, the bottom distance security zone 0, Width 240, height 180:



IPhone X-bottom.png

Run the results on iphone x:


IPhone X-safearea.png

Use security zones for auto layout layout, on iphone 8,iphone x and avoid the status bar/fringe/bottom of the home virtual gesture area, so that developers do not care about the status bar and fit the iphone x to avoid the height of bangs, Just place the child control in the security area specified by the Apple settle down, and the layout is ready.

The Safearealayoutguide property of UIView

See UIView's new two properties for safe area on iOS11:

@property (nonatomic,readonly) UIEdgeInsets safeAreaInsets API_AVAILABLE(ios(11.0),tvos(11.0));@property(nonatomic,readonly,strong) UILayoutGuide *safeAreaLayoutGuide API_AVAILABLE(ios(11.0),tvos(11.0));

Obviously this read-only Safearealayoutguide property is automatically created by the system and allows developers to use code to automate layout based on security zones.
Click on the Controller's view trigger Touchesbegan for print verification:

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{    NSLog(@"safeAreaInsets %@",NSStringFromUIEdgeInsets(self.view.safeAreaInsets));    NSLog(@"safeAreaGuide %@",self.view.safeAreaLayoutGuide);}打印结果:safeAreaInsets {44, 0, 34, 0}safeAreaGuide <UILayoutGuide: 0x6080009a3c60 - "UIViewSafeAreaLayoutGuide",layoutFrame = {{0, 44}, {375, 734}}, owningView = <UIView: 0x7f888240c3b0; frame = (0 0; 375 812); autoresize = W+H; layer = <CALayer: 0x608000431ec0>>>

According to the results of the printing, safeareainsets.top=44 is exactly the distance that Apple has set to match the fringe that iphone x avoids.
Safeareainsets.bottom=34, which is exactly the height of the home virtual gesture area at the bottom.

Horizontal screen Rotation test:

After a horizontal screen switch:



Lascape-1.png

Click on the Controller's view trigger Touchesbegan again for print verification, print the result:

safeAreaInsets {0, 44, 21, 44}safeAreaGuide <UILayoutGuide: 0x6080009a3c60 - "UIViewSafeAreaLayoutGuide", layoutFrame ={{44, 0}, {724, 354}}, owningView = <UIView: 0x7f888240c3b0; frame = (0 0; 812 375); autoresize =W+H; layer = <CALayer: 0x608000431ec0>>>

After the rotation, the safeareainsets.left distance from the Fringe isolation area is still 44, the bottom of the home virtual gesture area becomes 21.
This proves that the system also automatically calculates the situation of the screen rotation.

    • New security Zone Change method after IOS 11.0

1234 UIViewController中新增:- (void)viewSafeAreaInsetsDidChange;UIView中新增:- (void)viewSafeAreaInsetsDidChange;
    • Change the location of the view by changing the security zone

If the screen rotates, the corresponding security area will also change, so don't worry about it. [Safearea.gif] (http://upload-

12345678 images.jianshu.io/upload_images/1186277-ab32b1be56378531.gif?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)- (void)viewSafeAreaInsetsDidChange {    [superviewSafeAreaInsetsDidChange];        NSLog(@"viewSafeAreaInsetsDidChange-%@",NSStringFromUIEdgeInsets(self.view.safeAreaInsets));        [self updateOrientation];}
1234567891011121314 /** 更新屏幕safearea frame */- (void)updateOrientation {    if (@available(iOS 11.0, *)) {        CGRect frame = self.customerView.frame;        frame.origin.x = self.view.safeAreaInsets.left;        frame.size.width = self.view.frame.size.width - self.view.safeAreaInsets.left - self.view.safeAreaInsets.right;        frame.size.height = self.view.frame.size.height - self.view.safeAreaInsets.bottom;        self.customerView.frame = frame;    else{        // Fallback on earlier versions    }}

Summarize

This time in order to fit the iphone X, individuals from the beginning to see the concept of iOS11 safe area, traced back to IOS7 Toplayoutguide/bottomlayoutguide, learn from the beginning, benefited. We also learned about the UI adaptation of Apple engineers, a series of explorations for developers, and an optimized mental journey. Also see how they will be a good idea, facing the current demand changes, to carry out a reasonable expansion of the design of the flexible Extensible API:
1.ios7:toplayoutguide/bottomlayoutguide, using a virtual view to initially solve the navigation bar, Tabbar the isolation problem.

2.ios9: With the idea of virtual view, but also consider whether can remove the limitations of top/bottom concept, so that developers can flexibly customize the isolation area, but also provide some more convenient and easy to understand the API to facilitate the automatic layout of the code, so there is uilayoutguide this class.

3. Two years later, with the iphone X, Apple engineers took advantage of their iOS11 in iOS9, customizing a uilayoutguide to provide developers with a read-only attribute of Safearealayoutguide, And put forward the concept of safe area.

Reference Links:Https://stackoverflow.com/questions/46184197/ios-11-safe-area-layout-guide-backwards-compatibility

iOS development-layoutguide (from Top/bottom layoutguide to safe area)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.