About iOS Automatic Layout

Source: Internet
Author: User

Here is a Demo that implements automatic layout through code. I won't talk about it if I do it through IB. There are a lot of online materials. Here is a good link to write, if you are interested, let's take a look.

IOS7 Automatic Layout tutorial (1)

IOS7 Automatic Layout tutorial (2) -- English


To talk about automatic layout, the basic view is the first step.

/// NESMainViewController. m // AutoLayout // Created by Nestor on 14-3-2. // Copyright (c) 2014 NesTalk. all rights reserved. // # import "NESMainViewController. h "@ interface NESMainViewController () @ property (nonatomic, retain) UIView * view1; @ property (nonatomic, retain) UIView * view2; @ property (nonatomic, retain) UIView * view3; @ end @ implementation NESMainViewController-(UIView *) view1 {if (! _ View1) {_ view1 = [[UIView alloc] initWithFrame: CGRectMake (10, 30,145,200)]; _ view1.backgroundColor = [UIColor greenColor];} return _ view1 ;} -(UIView *) view2 {if (! _ View2) {_ view2 = [[UIView alloc] initWithFrame: CGRectMake (165, 30,145,200)]; _ view2.backgroundColor = [UIColor yellowColor];} return _ view2 ;} -(UIView *) view3 {if (! _ View3) {_ view3 = [[UIView alloc] initWithFrame: CGRectMake (10,240,300,300)]; _ view3.backgroundColor = [UIColor blueColor];} return _ view3;}-(void) buildLayout {[self. view addSubview: self. view1]; [self. view addSubview: self. view2]; [self. view addSubview: self. view3];}-(void) viewDidLoad {[super viewDidLoad]; [self buildLayout];}-(void) didReceiveMemoryWarning {[super didreceivemorywarning]; // Dispose of any resources that can be recreated .} @ end


After reading this class, it is necessary to first talk about my code style. It may be troublesome for many programmers who have just developed iOS to read this part of the code ~ However, Encoding Based on this style is very beneficial.

First read this code

-(UIView *)view1{    if (!_view1) {        _view1 = [[UIView alloc] initWithFrame:CGRectMake(10, 30, 145, 200)];        _view1.backgroundColor = [UIColor greenColor];    }    return _view1;}


This code is often written, and the TableView proxy method can be used in the singleton. Here is the getter Method for rewriting @ property. In simple words, call the private member variable self. view1 to call this method, there are two benefits

1. separated the construction content of different methods, and the code level was more obvious.

2. Delayed loading: When and when to create, instead of creating in the ViewDidLoad method, the operation efficiency can be optimized for complex view controllers.


In the ViewDidLoad method

- (void)viewDidLoad{    [super viewDidLoad];    [self buildLayout];}

It is very simple. after calling the buildLayout method, you can see the method name. Here is the method used to initialize the view layout. Because the method starting with init in oc is regarded as the class initialization method, so I used build. Of course, this is a personal habit. It doesn't matter ~


The buildLayout method places the controls to be added to the view one by one.

-(void)buildLayout{    [self.view addSubview:self.view1];    [self.view addSubview:self.view2];    [self.view addSubview:self.view3];}

Here we can clearly see the benefits of initializing the view by rewriting the getter method, which controls are added at a glance, if you need to modify a control, you can directly locate the corresponding getter method to modify it, without having to search for several lines of code in a large amount of code.


Based on the Code layout, This layered effect can be achieved for a single view controller:



Continue with the topic.


The code is shown in the on-screen view.



It is the layout we need, but if the screen goes horizontally, the problem will occur.



Next, you need to adjust the code to complete the automatic layout. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + tNNpT1M2v6rKvC4uLtOmuMPKx9XiyrG68r + fingerprint + PGJyPgo8L3A + fingerprint + PGJyPgo8L3A + CjxwPsrXz8jQ6NKq1No8L3A + CjxwPjwvcD4KPHByZSBjbGFzcz0 = "brush: java;">-(UIView *) view1 {if (! _ View1) {_ view1 = [[UIView alloc] initWithFrame: CGRectMake (10, 30,145,200)]; _ view1.backgroundColor = [UIColor greenColor];} return _ view1 ;}Add the following code to other methods:

        _view1.translatesAutoresizingMaskIntoConstraints = NO;
It is used to prohibit AutoresizingMask from being converted to AutoLayout. in simple words, Autoresizing and AutoLayout are not a set of things, but they are converted by default. here we need to specify the AutoLayout system, disable automatic conversion.


Add the following content to the buildLayout method:

    NSDictionary *views = NSDictionaryOfVariableBindings(self.view,_view3,_view2,_view1);        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-10-[_view1(==_view2)]-10-[_view2]-10-|" options:0 metrics:0 views:views]];    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-30-[_view1(<=200)]-10-[_view3]-10-|" options:0 metrics:0 views:views]];    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-30-[_view2(<=200)]-10-[_view3]-10-|" options:0 metrics:0 views:views]];    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-10-[_view3]-10-|" options:0 metrics:0 views:views]];    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_view3(>=150)]-10-|" options:0 metrics:0 views:views]];

Step by step:

    NSDictionary *views = NSDictionaryOfVariableBindings(self.view,_view3,_view2,_view1);
A system macro definition is used here. NSDictionaryOfVariableBindings () is used to generate a dictionary. The key name is the same as the object identifier. For example, the generated dictionary form is {"self. view ": self. view, @ "_ view3": _ view3 ,...}, this dictionary should contain the parent view and all child views that require automatic layout,

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-10-[_view1(==_view2)]-10-[_view2]-10-|" options:0 metrics:0 views:views]];
Here, an automatic layout rule is added. You can see that there is a troublesome string parameter.

| Screen border

-Interval between 10 and 10 points

[_ View2] controls to be laid out. Here _ view2 must be exactly the same as the identifier used to generate the dictionary above

[_ View1 (= _ view2)] _ view1 serves exactly the same purpose as above, while () contains conditions that can be = a certain space, or a fixed value, of course, in addition to =, you can also use >=or <=;


After each part of the string is clearly explained, it is easy to understand more ~ The complete meaning of this sentence is as follows:

The distance between two views with the same width is 10 points, and the distance between the left and right sides of the view is also 10 points ~


In this way, both the portrait screen and the landscape screen will be automatically laid out according to such a standard.


It is worth noting that the view that can execute this layout must return a valid CGSize through the-(CGSize) intrinsicContentSize method, while the UIView returns 0 by default, therefore, if only horizontal layout rules are set, the UIView will not be displayed on the screen.

For UIView, you must set horizontal and vertical layout rules at the same time or write a custom View inherited from UIView and then override-(CGSize) intrinsicContentSize to achieve this effect.

However, UIButton and UILabel are not required. It is enough to set a horizontal one.


Let's look at the following sentence:

V: |-30-[_ view1 (<= 200)]-10-[_ view3]-10-|

V: The layout rule in the vertical direction.

For a brief explanation, the height of view1 cannot be greater than 200 points. It is 30 points away from the upper border. The distance between view1 and view3 is 10 points, and the distance between view3 and the bottom border is 10 points.

Therefore, the height of view3 can be automatically calculated by setting the height ceiling and spacing of view1. You can see other layout rules by yourself.

At the same time, if the layout rules of all sub-views are specified, there is no need to set the frame of the sub-view. The Initialization Method of each frame can be changed:

-(UIView *)view1{    if (!_view1) {        _view1 = [[UIView alloc] init];        _view1.backgroundColor = [UIColor greenColor];        _view1.translatesAutoresizingMaskIntoConstraints = NO;    }    return _view1;}

Thus, the automatic layout of the entire view is very easy to implement. In my opinion, it is much easier to use code for Automatic Layout than xib. You can choose one by yourself.


If you want to add a sub-view to view1, you also need automatic layout? The following code is very simple:

-(UIView *)view1{    if (!_view1) {        _view1 = [[UIView alloc] init];        _view1.backgroundColor = [UIColor greenColor];        _view1.translatesAutoresizingMaskIntoConstraints = NO;                UIView *view = [[UIView alloc] init];        view.backgroundColor = [UIColor magentaColor];        [_view1 addSubview:view];        view.translatesAutoresizingMaskIntoConstraints = NO;        NSDictionary *views = NSDictionaryOfVariableBindings(_view1,view);        [_view1 addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-10-[view]-10-|" options:0 metrics:0 views:views]];        [_view1 addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-10-[view]-10-|" options:0 metrics:0 views:views]];            }    return _view1;}

Now, the automatic layout is almost done here, as shown below:



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.