iOS Development UI Chapter-screen fit Autoresizing AutoLayout and Sizeclass text

Source: Internet
Author: User
Tags compact

1. autoresizing

Autoresizing was the solution to Apple's early UI layout, and IOS6 was perfectly capable of Because the iphone only has a 3.5-inch screen, and the mobile app rarely supports a horizontal screen, iOS developers don't have to fit the layout any more, and all UI controls can be laid out relative to the parent control, yes autoresizing is a layout solution relative to the parent control; Note: It can only be laid out relative to the parent control ;
***
In Xcode, you can also use the visual interface to adjust or control the code.

You need to close AutoLayout and Sizeclass when using autoresizing (if using xcode6)
They're in conflict with each other.

You can see through the picture that the only 6 lines that the autoresizing can adjust by visualization correspond to its 6 enumerated values.

typedefNs_options (Nsuinteger,uiviewautoresizing) {Uiviewautoresizingnone =0, uiviewautoresizingflexibleleftmargin = 1 << 0, uiviewautoresizingflexiblewidth = 1 << 1,  Uiviewautoresizingflexiblerightmargin = 1 << 2, uiviewautoresizingflexibletopmargin = 1 << 3, uiviewautoresizingflexibleheight = 1 < < 4, uiviewautoresizingflexiblebottommargin = 1 << 5};          

The outer 4 lines are used to set the distance between the top, bottom, left, and right of the current view distance from the parent control;
Internal two lines to set whether the view follows the parent control from the fit width and height;
The code can be passed View.autoresizingmask = ... To set the autoresizing value;
The function of the autoresizing is nothing less;
***
Example:
1: Keep the spacing between two equal-width and equal-height view fixed forever, the Red View and blue view, want to let the distance between them fixed through autoresizing is not good; because autoresizing is laid out relative to the parent control, It is not possible to establish a layout relationship between two sibling view;



You can see a horizontal screen and vertical screen is not enough to meet the needs, let alone screen size is also bigger
Of course, you might be able to do it through other complex AIDS, but it's a hassle; it's not just a screen; screen size changes;
Autoresizing to this end, it is clear that it is nearly obsolete, to understand it;
***

2. After AutoLayout iOS6

One of the benefits of doing Apple development is having a good owner, Apple, who not only pays attention to the user experience, but also does not forget to remove some unnecessary hassles for developers (for example, the advent of arc ...)
AutoLayout: You can create a layout relationship between any of the two controls, either parent-child view or sibling view, a lot more powerful, and of course the cost of learning is much higher;
:

For the convenience of understanding the first tick AutoLayout on it, Sizeclass first stop tick (if it is xcode6)
The AutoLayout setting function is in the red box below;
***

First from left:


It is shown by the red box in the picture, where the function is to set the alignment between multiple view, so set the time to select more than one view to set

The second one:

This part is equivalent to a autoresizing, the strength is that can be any two view relative layout, you can set the distance from the parent control of the left and right position (red box), as well as its own height, but also relative to other controls to set the width height (blue box)

The third one:


This section is used to add, remove, and update constraints, the upper part is the constraint update for the selected view, and the bottom is the constraint for all view in the container

In addition to the top, you can also use the control button with the drag line to do AutoLayout:

===
Example: Using AutoLayout to complete the task just autoresizing can not be completed, here continue to increase the difficulty, in addition to the Red View and blue view, such as wide and so on, and the distance is always unchanged, but also to let two view overall vertically centered on the screen First, look at the final

Horizontal screen effect

You can see whether it is horizontal screen vertical screen or large screen small screen, are no problem, to the middle of the line distance fixed and equal;
***
Start with step-by-step AutoLayout completion

The first step:

First let two view and other high-width, in Xcode at the same time check the Red view and blue view, tick equal width, and so on;

这里也可以用另外一种方式:按住control进行拖线,为了可读性和看着直观就不用了;
At this point, please look at the upper left corner of Xcode, there will be a red arrow appears, indicating that the added constraints are incomplete, first of all: the integrity of the constraint, a view in the location of the position is relatively fixed (width and height and relative position), then the constraint is complete, attention is 相对固定 ; And here we just let two view and so on and so on, where there is no explanation, the constraints of course incomplete; so there is a red error;


Knowing that the red error arrows are normal, we continue, add each constraint is an entity, you can see in the view, click on each constraint can see in the right side of Xcode the constraints of the linear formula, this linear formula is the wisdom of Apple engineers crystallization, Clever use of mathematical wisdom worthy of our learning and experience;

Following these text boxes from top to bottom, you can get a linear formula (priority precedence does not count into formulas):
view.width Equal view.width * 1 + 0
To resolve:
view.width = view.widthIn this way to achieve the two view of the width of the relationship between the description, the formula into the code should be very easy to do it. Ha ha

Note: Here we look at the width constraint, so it is view.width, two views can be considered as Red view and blue view, can be swapped with each other position
Perhaps the above-mentioned formula is difficult to understand, then assume that the width of the red view is X, the blue view is the width of y, for any two real number x, Y, you can use the following linear formula (or a linear function) to represent their relationship:
y = k·x + bwhere k is the coefficient (that is, the multipliter in), B is the constant (is the constant in);
This is the primary school has learned a function, can meet any two view of any margin relationship;

Step Two:
After understanding these, back to the point, just added two view width and so on, and then, in order to ensure that there is no confusion, we can one to complete the constraint, here first fixed red view:
Here's how to use control to drag the line:

Here we let the red view and blue CenterY to the parent view of the CenterY is 70, so that the equivalent of two view in the vertical position fixed, the horizontal direction and the height of each view is not fixed, so the upper left corner of Xcode continue to report red error
Step Three:
Fixed horizontal position and width height, here fixed wide height, only need to fix one of them, because two view of the width of the same;

You can see the red arrow turns yellow when you finish adding it, which means that the constraint is only one step below the update, which you can do by clicking the yellow arrow Update or

Well, that's it. This looks like only two view, but the demand is already relatively complex;

Case TWO:
Through the above case one can see that AutoLayout can set any two view between the constraints, can be said to achieve any desired layout;
Bottom case: Let four view always divide the screen:
(to illustrate the effect, a pixel spacing is left in the middle):

Idea: First fix one of them, then other view and this view equal width, and then set the relative parent control constraints;

Code Implementation AutoLayout

Each constraint is a: Nslayoutconstraint object

NSLayoutConstraint *layout = [NSLayoutConstraint constraintWithItem:(id) attribute:(NSLayoutAttribute) relatedBy:NSLayoutRelationEqual toItem:(id) attribute:(NSLayoutAttribute) multiplier:(CGFloat) constant:(CGFloat)];[self.view addConstraint:layoutConstraint]

The method is just the linear formula Y = k x + B of the code representation; So although it is very long, it is easy to read; Finally remember to add the constraint to the view, you must note that if the constraint is a parent-child view relationship, the constraint must be added to the parent view;
But using code to implement AutoLayout is really troublesome, just two examples, each example has more than 15 constraints, if implemented in code, to create more than 15 Nslayoutconstraint objects, but also to clarify the relationship, can not write wrong Apple also took this into account for the developers, and launched the VFL language for the sake of writing AutoLayout;

VFL

Strictly speaking, a grammar similar to regular expressions specifically used to write AutoLayout, but the VFL does not bring simplification, its complexity is basically a line of writing do not want to write the second line of the degree:

NSString *vfl1 = @"|-hPadding-[_headerL]-hPadding-|";   [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:vfl1options:0 metrics:metrics views:dict1]]; 

Similar to regular usage, first write some matching rules with a string, and then call the next method to parse the rule to the view; I personally have always thought that programming language should be simple, the complexity of things to shield off, so that we develop more efficient, but also more time to deal with the good business; After all, what we do every day is to make the user simple, to leave the complexity to themselves;

A label with AutoLayout constraints, will automatically calculate the width of the high, and the top and bottom will not leave blank;

3. Unity of Apple Interface design: Sizeclass

With the development of science and technology, the distance between any two points in the space is narrowed, so that communication and information transmission are more convenient; it is more urgent to promote the progress of science and technology because of the need for communication and information transmission. Large screen is obviously a typical example, the relative increase of screen size, to a certain extent convenient communication and information transmission, conversely, Relatively small screen on the transmission of information will have a certain limit, so Apple launched a large-screen mobile phone is also the need for human progress, not what follow, the end of the nonsense;
The screen is big, the size is much, the nature that brings to the developer is the workload and thinking of the adaptation aspect; As you know, Apple is one of the most sought-after companies, and of course he will come up with a workable solution that is sizeclass;
Sizeclass: The screen size has been abstracted: not rigidly specific size, because the size has been changing, if we follow the size of the adaptation, it will be very tired;

Sizeclass an abstract classification of the screens for iOS devices:

  1. Compact (tight-small)
  2. Any (optional)
  3. Regular (Loose-Large)

Summarize several points:

    • Sizeclass is just the abstract classification of the screen, the specific screen to adapt to the use of AutoLayout;
    • Without the concept of the screen, there is no specific size, not to talk about the specific iphone5 or the ipad Air;
    • The height and width are abstracted to the top of the 3 kinds, 3*3 that is a total of 9 types, is 9 types, not 9 screen size;

      The result of this is that you can do a interface builder fit, and then you can use it both on the iphone and on the ipad;
      This is Apple's will; open Xcode if you create a new universal project, you will default to two storyboard before Xcode6, one for the iphone, one for the ipad, and one for the Xcode6, and a square, This means that no matter what screen size app you do (whether it's an ipad or iphone), it's just one storyboard.

      Learn 3 kinds of abstractions:

      What it looks like in Xcode:

      ***
      In specific terms:

The 9 squares in the figure represent the 9 abstractions of 3*3, each of which represents the meaning that can be checked;
Like the iphone's vertical screen, it's so abstract: compact Width * Regular height

Through the Sizeclass to classify the screen, and then use the AutoLayout to fit the layout, can say to achieve any desired effect, and do not distinguish between the device and do different IB, an IB all done, whether it is the iphone or the ipad;
Case:

There is a view 100 * 100 , the iphone vertical screen in the upper left corner, horizontal screen in the lower right corner, the ipad is in the middle;

such as the past seems to be abnormal requirements, now is a piece of cake;

    • Step one: Handle the vertical screen situation
      Sizeclass fixed screen for iphone vertical screen: compact Width | Regular Height

      Then add view to IB, with AutoLayout fixed size 100 * 100, and in the upper left corner, here let it left 20, 20;

      Then update frame to
      The sizeclass of the back is just the right choice.
      ***
      IOS8 added Sizeclass, the control also has a number of properties, on the storyboard to a label out (in the case of label), select, in the right menu area can be seen: installed, this is used to control the change control under what circumstances to display, the current nothing is constrained , means any * any, whether it is the size of the iphone or ipad size can be displayed, click on the left side of the small plus + can be used Sizeclass control what the situation is displayed, the same font, picture display;

      Display different fonts on different screens:

      ... There are a lot of similar features
      The idea of this function is similar to the three states of UIButton (normal, highlighted, selected), except there are 9 states;
      ***

      XCODE6 Preview

      When the type of screen becomes more and more rich, if you want to see the adaptation between different screens, in the past is to constantly switch the simulator, and then run to see the effect, and switch the simulator is a very time-consuming thing; After xcode6, we can not run directly to see the adaptation of the situation;
      For just the case to operate can not run to see the adaptation effect;

Code Preview @IBDesignable and @ibinspectable

These two properties are the new features of Xcode6
If you do not create a view through IB, but rather create a view through code, how to render it in real time without running the program on IB, through @ibdesignable and @ibinspectable; @IBDesignable Tell interface The builder class can be rendered to the interface in real time, but this class must be a subclass of UIView or NSView. By @ibinspectable, you can define dynamic properties to visualize and modify property values in the Attribute Inspector panel.

Example (written by Swift): This example customizes a subclass of UIView, which has a UIButton

@IBDesignableClassMycustomview:UIView {@IBInspectablevar Buttontitlecolor:uicolor!Button title Color@IBInspectablevar buttontitle:string!Button title@IBInspectablevar buttonframe:cgrect!Button framevar MyButton:uibutton!OverrideInit (frame:CGRect) {Init stored Properties Buttontitlecolor =Uicolor.redcolor () Buttontitle ="I am the button" Buttonframe =CGRectMake (0,0,100,MyButton =UIButton (Frame:buttonframe) Mybutton.settitlecolor (Buttontitlecolor, forstate:.Normal) Mybutton.settitle (Buttontitle, forstate:.Normal)Call Super initializerSuper.Init (Frame:frame)Add button to self Addsubview (MyButton)}RequiredInit (coder Adecoder:Nscoder) {Init stored Properties Buttontitlecolor =Uicolor.redcolor () Buttontitle ="button title" Buttonframe =CGRectMake (0,0,100,50) MyButton = uibutton (frame:buttonframe) Mybutton.settitlecolor (Buttontitlecolor, forstate:.  Normal) Mybutton.settitle (Buttontitle, forstate:.  Normal) //call Super initializer super. Init (coder:adecoder) //add button to self Addsubview (MyButton)} override func layoutsubviews () {//refresh button State through Attribute Inspector Mybutton.settitlecolor (Buttontitlecolor, forstate:.  Normal) Mybutton.settitle (Buttontitle, forstate:.  Normal)}}                

The class adds a button to the interface, adding three attributes, color, title, frame, all of the three attributes are used to describe the button, and the front plus @ibinspectable means that it can be previewed in real time in IB without having to run the program to start the emulator;
Also rewrite the DrawRect method to draw a rectangle;
This time open storyboard, add a view (in order to control the size of the GIF graph, the view in the picture has been added to the constraints, and the background color changed to blue, easy to identify); Modify class to Mycustomview; the preview will appear At the same time we will begin to draw the rectangle to the ellipse, and then look at the storyboard again, the preview has become an ellipse, it is very cool, do not waste time waiting for the simulator to start to observe the layout of the UI;

Size and rate of each Apple device

A picture wins thousands of words

***

iOS Development UI Chapter-screen fit Autoresizing AutoLayout and Sizeclass text

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.