Although the automatic layout has been introduced in iOS6, it has not been widely used by the development team for various reasons. On the one hand is everyone's app support version is below IOS6, on the other hand is Xcode support Wood has now so good. Previously, because the iphone device is relatively fixed, so in pure code, the layout of the pure coordinates is very popular, but now with the release of IPhone6, if you want to write a lot of messy absolute coordinates to fit, the workload and maintenance costs are very large.
Some of the following basis directly with small partners to share the tidy bar, and then recommend an open source library, the AutoLayout is packaged, easy to use and efficient.
What is 1.AutoLayout? Use an official Apple definition.AutoLayout is a constraint-based, descriptive layout system. Auto Layout is a constraint-based, descriptive layout System.Keywords:
- Based on constraints-and the position and size of the previously defined frame, the position of the AutoLayout is defined by the so-called relative position constraints, such as the x-coordinate of the center of Superview, the y-coordinate is 10 pixels above the bottom of the screen, etc.
- Descriptive-constraint definitions and individual view relationships are described using approaches to natural language or visual language (VFL)
- The layout system-that is, the literal meaning, is responsible for the position of each element of the interface.
In summary, AutoLayout provides developers with a layout method that differs from the traditional placement of UI element locations. Previously, whether you were dragging or dropping in IB or writing in code, each uiview had its own frame property to define its position and size in the current view. With AutoLayout, it becomes the use of constraints to define the location and dimensions of the view. Such a
The biggest benefit is that it solves the problem of view adaptation in different resolutions and screen sizes, and simplifies the definition of the position of the view when rotating., the view, which is centered 10 pixels above the bottom, is always centered 10 pixels above the bottom, regardless of whether it is rotating the screen or changing the device (ipad or IPhone5 or the mini ipad that may appear later). Summarizing the use of constraints to describe the layout, the view frame is calculated based on these constraints describe the layout with constraints, and frames is calculated The difference between automatically.1.1autolayout and autoresizing mask before iOS6, the adaptation of screen rotation and the automatic adaptation of the Iphone,ipad screen are basically done by autoresizing mask. But with the increasing demands for iOS apps, and the devices that have been and are likely to appear in multiple screens and resolutions in the future, autoresizing mask is a bit outdated and dull. AutoLayout can do all the work that the original autoresizing mask can do, and also be able to perform tasks that were previously impossible, including:
- AutoLayout can specify the relative position of any two view without needing two view in the immediate view hierarchy like Autoresizing mask.
- AutoLayout does not have to specify a constraint on an equality relationship, it can specify a non-equality constraint (greater than or less than, etc.), and the layout that autoresizing mask can make can only be of equal condition.
- The AutoLayout can specify the precedence of the constraint, and the calculation of the frame takes precedence over the condition that satisfies the high priority.
Summary autoresizing Mask is a subset of AutoLayout, any work that can be done with autoresizing mask can be done with AutoLayout. AutoLayout also has some excellent features that autoresizing mask does not have to help us build interfaces more easily 2. Fundamentals
Suppose there is a button that you want to place in the center of the screen. The relative position of the View Center and button Center can be simply defined as follows:
• The center.x of the button corresponds to the center.x of the View Center
• The center.y of the button corresponds to the center.y of the View Center
Apple has found that many of the UI component locations can be resolved using a simple equations equation:
Item1.attribute = multiplier? Item2.attribute + constant
For example: With this equation, we can easily place a button in his parent view, as follows:
button.center.x= (button.superview.center.x*1) +0 button.center.y= (button.superview.center.y*1) +0
That is: y = m*x + b
3. Related knowledge
3.1 Adding a description using a linear formula
Method: Constraintwithitem
[Nslayoutconstraint Constraintwithitem: (ID) attribute: (nslayoutattribute) Relatedby: ( nslayoutrelation) Toitem: (ID) attribute: (nslayoutattribute) multiplier: (cgfloat ) constant: (cgfloat)];
(Item1.attribute = multiplier? Item2.attribute + constant)
Nslayoutattribute:
typedef
NS_ENUM(NSInteger, NSLayoutAttribute) {
NSLayoutAttributeLeft = 1,
//左侧
NSLayoutAttributeRight,
//右侧
NSLayoutAttributeTop,
//上方
NSLayoutAttributeBottom,
//下方
NSLayoutAttributeLeading,
//首部
NSLayoutAttributeTrailing,
//尾部
NSLayoutAttributeWidth,
//宽度
NSLayoutAttributeHeight,
//高度
NSLayoutAttributeCenterX,
//X轴中心
NSLayoutAttributeCenterY,
//Y轴中心
NSLayoutAttributeBaseline,
//文本底标线
NSLayoutAttributeNotAnAttribute = 0
//没有属性
};The difference between the nslayoutattributeleading/nslayoutattributetrailing is that left/right always refers to the left and right, leading/trailing in certain areas (Hebrew, etc.) that are accustomed to it. Leading is to the right, trailing is left nslayoutrelation:
typedef
NS_ENUM(NSInteger, NSLayoutRelation) {
NSLayoutRelationLessThanOrEqual = -1,
//小于等于
NSLayoutRelationEqual = 0,
//等于
NSLayoutRelationGreaterThanOrEqual = 1,
//大于等于
};Requirement: button is always in the center of the screen<demo mainvc>@interface UIView (uiconstraintbasedlayoutinstallingconstraints)
-(Nsarray *) Constraints Ns_available_ios (6_0);
-(void) AddConstraint: (Nslayoutconstraint *) constraint Ns_available_ios (6_0);
-(void) Addconstraints: (Nsarray *) Constraints Ns_available_ios (6_0);
-(void) Removeconstraint: (Nslayoutconstraint *) constraint Ns_available_ios (6_0);
-(void) Removeconstraints: (Nsarray *) Constraints Ns_available_ios (6_0);
@end when adding a target view to follow the following rules: 1. For the constraint relationships between the two same-level view, add to their parent View 2. For the constraint relationships between two different levels of view, add to their nearest common parent view 3. For a hierarchical relationship between the two view constraints, add to the higher-level parent view simply, look for the parent class.<Demo,ButtonVC> two button3.2 Use visual format Language to define horizontal and vertical constraints Visual format Language visual formatting language, used to describe constraints, a language that is an abstraction of a visual description, as the approximate process looks like: two-button spacing Horizontal standard spacing between cancel and accept: [Cancelbutton]-[acceptbutton] Official document: Visual Format Syntax
The following is examples of constraints you can specify using the visual format. Note how the text visually matches the image.
-
Standard Space
-
[Button]-[textfield]
-
Width Constraint
-
[button (>=50)]
-
Connection to Superview
-
|-50-[purplebox]-50-|
-
Vertical Layout
-
V:[topfield]-10-[bottomfield]
-
Flush views
-
[Maroonview][blueview]
-
priority
-
[Button ([EMAIL&N Bsp;protected])]
-
Equal Widths
-
[button1 (==button2)]
multiple predicates
-
[Flexiblebutton (>=70,<=100)]
-
A complete L Ine of Layout
-
|-[find]-[findnext]-[findfield (>=20)]-|
Example: vfl:email:h:|-[_textfieldemail]-| V:|-100-[_textfieldemail] Confirm email:h:|-[_textfieldconfirmemail]-| V:[_textfieldemail]-[_textfieldconfirmemail] Register Button:v:[_textfieldconfirmemail]-[_registerbutton] Defects: 1. Cannot express is a fixed aspect ratio, such as: Imageview.width = 2 * ImageView.height2.UI The middle condition of the component in the horizontal direction cannot be defined by Visual Format Language 3. ... Method: VISUALFORMAT:VFL Visual Format Language nslayoutformatoptions:typedef ns_options (Nsuinteger, nslayoutformatoptions) {
Nslayoutformatalignallleft = (1 << nslayoutattributeleft),
Nslayoutformatalignallright = (1 << nslayoutattributeright),
Nslayoutformatalignalltop = (1 << nslayoutattributetop),
Nslayoutformatalignallbottom = (1 << nslayoutattributebottom),
nslayoutformatalignallleading = (1 << nslayoutattributeleading),
nslayoutformatalignalltrailing = (1 << nslayoutattributetrailing),
Nslayoutformatalignallcenterx = (1 << nslayoutattributecenterx),
Nslayoutformatalignallcentery = (1 << nslayoutattributecentery),
Nslayoutformatalignallbaseline = (1 << nslayoutattributebaseline),
Nslayoutformatalignmentmask = 0xFFFF,
/* Choose only one of these three
*/
nslayoutformatdirectionleadingtotrailing = 0 <<,//default
Nslayoutformatdirectionlefttoright = 1 << 16,
Nslayoutformatdirectionrighttoleft = 2 << 16,
Nslayoutformatdirectionmask = 0x3 << 16,
}; Note: The vertical direction for Left,right,leading,trailing,centerx is top,bottom,centery,baseline in horizontal direction (BaseLine is aligned to the bottom of the text) Metrics
[constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-padding-[messageTextView]-kTopAndBottomPadding-|" options:NSLayoutFormatAlignAllTop metrics:@{@"padding":@5.0} views:variableBindings]];
Views:a Dictionary of views it appear in the visual format string. The keys must is the string values used in the visual format string, and the values must be the view objects.Example 1:V:[_textfieldemail]-[_textfieldconfirmemail]nsdictionary *viewsdictionary = Nsdictionaryofvariablebindings (_ Textfieldconfirmemail, _textfieldemail); Example 2:h:|-[_textfieldemail]-| Nsdictionary *viewsdictionary = nsdictionaryofvariablebindings (_textfieldemail);Method Prototypes: /* This macro was a helper for making view dictionaries for +constraintswithvisualformat:options:metrics:views:.
Nsdictionaryofvariablebindings (v1, v2, v3) is equivalent to [nsdictionary dictionarywithobjectsandkeys:v1, @ "v1", V2, @ " V2 ", V3, @" V3 ", nil];
*/
#define Nsdictionaryofvariablebindings (...) _nsdictionaryofvariablebindings (@ "" # __va_args__, __va_args__, nil)
Uikit_extern nsdictionary *_nsdictionaryofvariablebindings (nsstring *commaseparatedkeysstring, id firstValue, ...) Ns_available_ios (6_0); Not-for-direct use
<demo firstvc> two x textfiled, one button<demo thirdvc> parameter: nslayoutformatoptions: comparison of two methods of <demo buttonvc> <demo secondvc> use view from different parent classes to constrain3.3 Nslayoutconstraint (over) 4.XIB use the layout4.1 using method 4.2 fix 5. Error prone because of the constraints involved, so all possible problems under the constraint model will appear here, specifically including two kinds: *) Am Biguous layout cannot be determined *) unsatisfiable Constraints Unable to satisfy constrained layout cannot be determined to refer to the given constraints cannot uniquely determine a layout, that is, the constraints are insufficient to get the unique layout results. This situation generally adds some necessary constraints or adjustment priorities that can be resolved. The problem source that can not satisfy the constraint is that there are constraints conflicting with each other, so it is not possible to satisfy at the same time, some constraints need to be removed. Both errors can cause layout instability and errors when they occur, ambiguous is tolerated and a viable layout is chosen to render on the UI, and unsatisfiable will not be able to get the UI layout and error.
Uiview+autolayout (GitHub address: https://github.com/smileyborg/UIView-AutoLayout)
This third-party-written class encapsulates the constraints of a view that requires code creation. If you use code to set constraints, with a visual language, less code, if the team members are familiar with the case, readability is OK! Use another method to create a constraint, and then add a view, though readable, But the code is large. And this category is a more readable approach to those methods, and the original intention of automatic layout, as long as you call the simple method to describe the relationship between the different view, and create the constraints of the method, we do not need to care. The author also adds an array of categories, which are used to create constraints for multiple view creation. Specifically, you can download it directly to GitHub and see the demo of the sample.
iOS Auto-layout learning (uiview+autolayout)