[IOS development] AutoLayout (Code-only) and iosautolayout

Source: Internet
Author: User

[IOS development] AutoLayout (Code-only) and iosautolayout

For AutoLayout, it was first introduced from iOS6.

The main function is to use constraints to relatively layout the view to adapt to the transformation of different screens. A large amount of information on the Internet is being introduced to xib and storyboard. How to Use AutoLayout, that is, there are fewer and fewer pure code uses AutoLayout for UI layout. For someone who is used to code UI layout, write a memo: What is AutoLayout? Use an official definition of Apple
AutoLayout is a constraint-based and descriptive layout system. Auto Layout Is a Constraint-Based, Descriptive Layout System.
Keywords:
  • Based on constraints-unlike the previously defined frame positions and sizes, the AutoLayout position is defined based on the so-called relative position constraints. For example, the x coordinate is the center of superView, y coordinates are 10 pixels above the bottom of the screen.
  • Descriptive-the definition of constraints and the relationship between views are described using methods that are close to natural or visual language (will be mentioned later ).
  • Layout System-literally, used to take charge of the location of each element on the interface.
All in all, AutoLayout provides developers with a layout method different from that specified by the traditional UI element location. In the past, both drag and drop in IB and write in code, each UIView has its own frame attribute to define its position and size in the current view. If AutoLayout is used, it is changed to defining the position and size of the view using constraints. The biggest advantage of this is that it solves the adaptation problem of different resolutions and screen sizes, and also simplifies the definition of the position of the view during rotation. The original 10-pixel center view on the bottom, no matter when you rotate the screen or change the device (iPad or iPhone 5 or a mini iPad may appear later), the position remains at the center of 10 pixels above the bottom. Summary
Use constraints to Describe the layout. the view frame calculates Describe the layout with constraints, and frames are calculated automatically.
The difference between AutoLayout and Autoresizing Mask is our old friend... If you have been writing code to the UI before, you must have written enumerations such as UIViewAutoresizingFlexibleWidth. If you used more IB, we have noticed that each view's size inspector has a red Autoresizing indicator and corresponding animation scaling, Which is Autoresizing Mask. Before iOS6, the adaptation to screen rotation and the automatic adaptation of iPhone and iPad screens were basically completed by Autoresizing Mask. However, with the increasing requirements on iOS apps and various screens and resolutions that may appear in the future, Autoresizing Mask seems outdated and dull. AutoLayout can complete all the work that was previously completed by Autoresizing Mask and be competent for some tasks that were not previously completed, including:
  • AutoLayout can specify the relative positions of any two views, instead of having two views in the direct view hierarchy as Autoresizing Mask does.
  • AutoLayout does not have to specify equal constraints. It can specify non-equal constraints (greater than or less than), while Autoresizing Mask can only perform equal conditions.
  • AutoLayout can specify the priority of a constraint. When calculating a frame, the priority is calculated based on the conditions that meet the priority.
Summary
Autoresizing Mask is a subset of AutoLayout. Any work that can be completed by Autoresizing Mask can be completed by AutoLayout. AutoLayout also has some excellent features that Autoresizing Mask does not possess to help us build interfaces more conveniently.
The AutoLayout basic usage method Interface Builder refers to a large number of online tutorials.
Manually use APIs to add constraints to create a new class in iOS6: NSLayoutConstraint, a constraint in the form
  • Item1.attribute = multiplier? Item2.attribute + constant
The corresponding code is
1 [NSLayoutConstraint constraintWithItem:button
2                              attribute:NSLayoutAttributeBottom
3                              relatedBy:NSLayoutRelationEqua
4                                 toItem:superview
5                              attribute:NSLayoutAttributeBottom
6                             multiplier:1.0
7                               constant:-padding]
The corresponding constraint is "bottom of button (y) = bottom of superview-10 ". After creating a constraint, you must add it to the view to which the constraint is applied. UIView (also NSView) adds a new instance method:
  • -(Void) addConstraint :( NSLayoutConstraint *) constraint;
Used to add constraints to the view. Note that the added target view must follow the following rules:
  • Add constraints between two views at the same level to their parent view.
 
  • Add constraints between two views of different levels to their closest parent view.
 
  • Add constraints between two views with hierarchies to parent views with higher hierarchies.
 
You can use the-setNeedsUpdateConstraints and-layoutIfNeeded methods to refresh the changes in constraints and relay the UIView. This is the same as CoreGraphic's-setNeedsDisplay ~ Visual Format Language UIKit team has a lot of love this time. They also think that the name of the newly added API is too long, so they have invented a new way to describe constraints, very interesting. This language is an abstraction of the visual description. The general process looks like this: the accept button is at the default Spacing on the right side of the cancel button.
 


Finally, the VFL (Visual Format Language) is described as follows:
1 [NSLayoutConstraint constraintsWithVisualFormat:@\\"[cancelButton]-[acceptButton]\"
2                                         options:0
3                                         metrics:nil
4                                           views:viewsDictionary];
ViewsDictionary is a dictionary bound with the view name and object. For this example, you can use the following method to obtain the corresponding dictionary:
1 UIButton *cancelButton = ...
2 UIButton *acceptButton = ...
3 viewsDictionary = NSDictionaryOfVariableBindings(cancelButton,acceptButton);
The generated dictionary is
{ acceptButton = ""; cancelButton = ""; } 
Of course, if you are not tired, you can write your own handwriting. Now, the dictionary, array, and writing are much simpler, so it is not complicated. For more information about the new syntax of Objective-C, see my previous WWDC 2012 Note: WWDC 2012 Session Note -- 405 Modern Objective-C. Adding parentheses and numbers at the link after the view name can give the expression more meaning. The following are some examples:
  • [CancelButton (72)]-12-[acceptButton (50)]
    • Cancel the 72-point button width, and the accept button width is 50 points. The distance between them is 12 points.
  • [WideView (> = 60 @ 700)]
    • If the width of the wideView is greater than or equal to 60 point, the priority of the constraint is 700 (the maximum priority is 1000, and the higher the priority, the more advanced the constraint is)
  • V: [redBox] [yellowBox (= redBox)]
    • Vertical layout: first, a redBox, followed by a yellowBox with the width equal to the redBox width
  • H: |-[Find]-[FindNext]-[FindField (> = 20)]-|
    • Horizontal layout: the default interval width between Find and the left edge of the parent view, followed by the default interval width between FindNext and Find, followed by the FindField with a width not less than 20, the spacing between it and FindNext and the right edge of the parent view is the default width. (Vertical bars '|' indicates the superview edge)
Errors that are easy to occur are caused by constraints. All possible problems in the constraint model are described as follows:
  • The Layout of Ambiguous Layout cannot be determined.
  • Unsatisfiable Constraints cannot meet the Constraints
The layout cannot be determined because the given constraints cannot uniquely determine a layout, that is, the constraint conditions are insufficient, and the layout results cannot be unique. In this case, you can add some necessary constraints or adjust the priority. Constraints cannot be met because constraints conflict with each other and cannot be met at the same time. You need to delete some constraints. When two errors occur, the layout is unstable and the layout is incorrect. Ambiguous can be tolerated and a feasible layout can be selected and displayed on the UI. Unsatisfiable cannot get the UI layout and report an error. For uncertain la S, you can pause the program during debugging and enter
  • Po [[UIWindow keyWindow] _ autolayoutTrace]
To check whether Ambiguous Layout exists and its location. There are also some check methods to view the constraints and constraints of the view:
  • [View constraintsAffectingLayoutForOrientation/Axis: NSLayoutConstraintOrientationHorizontal/Vertical]
  • [View hasAmbiguousLayout]
    • [View exerciseAmbiguityInLayout]
Layout animation is an important part of the UI experience, and the animation after the layout is changed is also critical. Speaking of Animation, Core Animation has made great achievements again .. since the appearance of CA, all animation effects are very cheap, and the situation in auto layout is the same as in collection view, very easy (see WWDC 2012 Session notes -- 219 Advanced Collection Views and Building M Layouts), just put layoutIfNeeded In the animation block ~
1 [UIView animateWithDuration:0.5 animations:^{
2     [view layoutIfNeeded];
3 }];
After some code pure code UI is normally laid out, you can add autolayout. The adjustment is quite convenient. This is a horizontal center. The four vertical button layout codes setTranslatesAutoresizingMaskIntoConstraints are no, and AutoLayou is enabled.

// ----- AutoLayout

[_ Btn_1 setTranslatesAutoresizingMaskIntoConstraints: NO];

[_ Btn_2 setTranslatesAutoresizingMaskIntoConstraints: NO];

[_ Btn_3 setTranslatesAutoresizingMaskIntoConstraints: NO];

[_ Btn_4 setTranslatesAutoresizingMaskIntoConstraints: NO];

CGSize winSize = [[iHappySDKSingle shareSingle] getScreenSize];

CGFloat tpo = _ btn_1.frame.origin.y;

CGFloat hpod = _ btn_1.frame.origin.x;

CGFloat btnH = _ btn_1.frame.size.height;

CGFloat vpod = winSize. width * 0.15-btnH;

NSNumber * tp = [NSNumber numberWithFloat: tpo];

NSNumber * hd = [NSNumber numberWithFloat: hpod];

NSNumber * vd = [NSNumber numberWithFloat: vpod];

NSNumber * bh = [NSNumber numberWithFloat: btnH];

NSNumber * btm = [NSNumber numberWithFloat: vpod * 2];

NSDictionary * dict1 = NSDictionaryOfVariableBindings (_ btn_1, _ btn_2, _ btn_3, _ btn_4 );

NSDictionary * metrics =@ {@ "hPadding": hd, @ "vPadding": vd, @ "top": tp, @ "btm": btm, @ "btnHeight ": bh };

NSString * vfl1 = @ "|-hPadding-[_ btn_1]-hPadding-| ";

[Self. view addConstraints: [NSLayoutConstraint constraintsWithVisualFormat: vfl1

Options: 0

Metrics: metrics

Views: dict1];

NSString * vfl2 = @ "|-hPadding-[_ btn_2]-hPadding-| ";

[Self. view addConstraints: [NSLayoutConstraint constraintsWithVisualFormat: vfl2

Options: 0

Metrics: metrics

Views: dict1];

NSString * vfl3 = @ "|-hPadding-[_ btn_3]-hPadding-| ";

[Self. view addConstraints: [NSLayoutConstraint constraintsWithVisualFormat: vfl3

Options: 0

Metrics: metrics

Views: dict1];

NSString * vfl4 = @ "|-hPadding-[_ btn_4]-hPadding-| ";

[Self. view addConstraints: [NSLayoutConstraint constraintsWithVisualFormat: vfl4

Options: 0

Metrics: metrics

Views: dict1];

NSString * vfl5 = @ "V: |-(<= top)-[_ btn_1 (btnHeight)]-vPadding-[_ btn_2 (btnHeight)] -vPadding-[_ btn_3 (btnHeight)]-vPadding-[_ btn_4 (btnHeight)]-(> = btm)-| ";

If (_ btn_1.hidden ){

Vfl5 = @ "V: |-(<= top)-[_ btn_2 (btnHeight)]-vPadding-[_ btn_3 (btnHeight)] -vPadding-[_ btn_4 (btnHeight)]-(> = btm)-| ";

}

[Self. view addConstraints: [NSLayoutConstraint constraintsWithVisualFormat: vfl5

Options: 0

Metrics: metrics

Views: dict1];

After the UI of the pure code is normally laid out, a function is added for automatic horizontal center layout: NSLayoutAttributeCenterX vertical center layout: NSLayoutAttributeCenterY and subsequent layout switching animations.

-(Void) setAutoLayoutForKuang :( UIView *) imgv

{

UIView * view = self;

[Imgv setTranslatesAutoresizingMaskIntoConstraints: NO];

NSDictionary * dict1 = NSDictionaryOfVariableBindings (imgv );

NSDictionary * metrics =@ {@ "width": [NSNumbernumberWithFloat: imgv. frame. size. width],

@ "Height": [NSNumber numberWithFloat: imgv. frame. size. height],

@ "Top": [NSNumber numberWithFloat: imgv. frame. origin. y]

};

NSString * vfl1 = @ "[imgv (width)]";

[View addConstraints: [NSLayoutConstraint constraintsWithVisualFormat: vfl1

Options: 0

Metrics: metrics

Views: dict1];

NSString * vfl2 = @ "V: [imgv (height)]";

[View addConstraints: [NSLayoutConstraint constraintsWithVisualFormat: vfl2

Options: 0

Metrics: metrics

Views: dict1];

[View addConstraint: [NSLayoutConstraint constraintWithItem: imgvattribute: NSLayoutAttributeCenterX relatedBy: NSLayoutRelationEqual toItem: viewattribute: extends multiplier: 1 constant: 0];

[View addConstraint: [NSLayoutConstraint constraintWithItem: imgvattribute: NSLayoutAttributeCenterY relatedBy: NSLayoutRelationEqual toItem: viewattribute: extends multiplier: 1 constant: 0];

// Animation

[UIView animateWithDuration: 0.25 animations: ^ {

[Imgv layoutIfNeeded];

}];

}

--------------------------------------- Related online articles: article 1, AutoLayout (Automatic Layout) Introduction recommendation 2, Autolayout and VFL experience sharing this article contains a demo (quick access to download) recommended 3, iOS 6 Auto Layout NSLayoutConstraint interface Layout is not a friend in worry manual some of these script-like characters: Now we recommend an Open Source library for everyone github: https://github.com/TelenLiu/Lytgit@OSC: http://git.oschina.net/TelenLiu/Lyt

Related Article

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.