This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!

AutoLayout profile

AutoLayoutDesigned to replaceAutoresizingSo in the same project,AutoLayoutandAutoresizingCan’t coexist. You have to choose one or the other. If you chooseAutoLayout, thenAutoresizingAutomatically blocked; If you chooseAutoresizing, thenAutoLayoutIt is automatically blocked.XCode5By default, new projects are usedAutoLayout


About constraints

Constraint concept

AutoLayout is implemented mainly by control reference and constraint, such as control A relative to control B, control A is directly below control B, spacing is 20px

Every time you add a constraint to a control in xiB or SB, you add a constraint object. For example, setting the width and height of A child control A in the XIB, as well as the spacing between the top, bottom, and left and right of the parent control, is equivalent to adding six constraints to the control, resulting in six constraint objects

Constraint error warning

  • Red arrow, constraint error, usually lack of constraint or constraint conflict (for example, 375 screen width, you can’t be 200 to the left, 200 to the right, and control width 100, definitely not)
  • The yellow arrow represents the constraint warning, indicating that the current control in the XIB renders the position or size is not the same as the actual effect of the program after running. The cause of the constraint warning is often that the control does not update the constraint, but it does not affect the real effect of the control, and it does not report an error

Note: Just because a constraint has an error does not mean it will run incorrectly

Rules of constraint

  • Added to the superview relative to the constraints of the superview

  • A constraint relative to another control is added to its shared superview

  • Constraints across hierarchies are added to their uppermost superview

  • Its own wide and high constraints are added to its own view

Constraints on special controls

By default, UILabel content is vertically centered. If you use Autolayout to set constraints on UILabel, you only need to set X, Y and width without setting height. UILabel will automatically wrap the contents and change with how small the contents are. If we set the width of the UILabel to 100, but the content is still too small to wrap, we can set the width to <=100. In this case, both the width and the height of the label can wrap the content. The same is true for height Settings. Of course, we can just set x and y for UILabel. However, you must ensure that the UILabel’s text property has content, otherwise the UILabel will not display (a common beginner’s mistake). The reason is that the width and height of UILabel are automatically adjusted according to the content. If there is no content, the width and height will be 0, resulting in the failure of UILabel display.


AutoLayout usage

XIBSet in theAutoLayout

Multiple control alignment processing

Handling of individual controls

Safe Area : In iOS11, safe area is a virtual view added to all views. The size of the virtual view depends on where the view is located. All custom controls are laid out as close as possible to the safe Area virtual view

Constrain to margins: default is 16px, iPhone6Pluse is ready, it’s likely to drop

User Standard Value: Use a Standard Value, and this Value is only useful when setting up and down directions. The default value is the distance from the Bottom Layout Guide. The lower baseline is the very bottom of the distance view. The upper baseline is the position below StatusView

User Current Canvas Value: Set using the Current location. Default to the nearest View in the current direction, and no occluded views are overridden

Note: the spacing between the upper and lower left and right and the width and height of the control are used together, and try not to conflict; For example: 375 screen width, you can not be 200 from the left, 200 from the right, and control width 100, definitely not

Suggestion: give the distance to the left, while giving the space width, applicable to the control, such as Lable, textField, do not consider how much it is to the right; If you give spacing to the left and right, don’t give width. This applies to controls such as Buttons.

Update, add, and clear constraints

Selected Views: Deals with the Constraints for the View you currently select. Clear Constraints deletes all Constraints for the Selected View

All Views in ViewController: Deals with All Views in the current ViewController. Clear Constraints deletes All Constraints from the current VC

Adaptive layout (Trait Variations)

The Trait Variations have replaced the Size Class. You can see the following models become more intuitive when matched with the adaptive size

Device: In Device, it is easy to assume that the feature variable is valid for a specific Device. In fact, it is not for a specific Device, but for a category of devices with the same Sizeclass, so adding the feature variable affects a category of devices

Interface Style: Bright or dark Interface Style

Orientation: Direction of the device

Vary for Traits: Select Width, Height, or both. The background will turn blue and the device displayed on the left will change. After selecting the device, click the Done Varying button

Example:

The general combination has 4 results (wC hC), (wR hR), (wC hR), (wR hC) (W is width, H is height, C is Compact, R is Regular)

  • (wC hR): It works with portrait iphones of any size

  • (wR hR): Applies to all landscape and portrait ipads

  • (wC hC): Works in landscape on iPhone (except for iPhone11, iPhone Plus, etc.)

  • (wR hC): Applicable to the landscape screen of iPhone 11 and iPhone Plus

    Example: If iPhone8 (wC hR)UI layout is used, and Width is selected for the classification button, then if iPhone8 UI is modified, it will cause the UI of the same wC device such as (wC hC), (wC hR) to change. If iPhone8 (wC hR)UI layout is used, and Width and Height are selected for the classification button, then if iPhone8 UI is modified, it will change the UI of devices with the same hR, such as (wR hR) and (wC hR). So if the UI of iPhone8 is modified, the UI of the same device (wC hR) will change

According to different layouts and different classification options, the influences on corresponding layouts are summarized as follows:

The UI layout Width Height Width & Height
CR CR, CC CR, RR CR
RC RC, RR RC, CC, RC
CC CC and CR CC, RC CC
RR RR, RC RR, CR RR

In different layouts, the same control can be set to different constant values to achieve the same effect, you can add the layout in the configuration, instead of adding two constraints

Use this when changing the properties of the control on different devices, such as when the font size is smaller on the iPhone portrait screen and larger on the iPhone landscape screenVary for TraitsWe just need to add the layout to the control property, and if we don’t need to delete it with a dot

If you want to specify the size and select a new control, you can do something similar at the bottom of the control property, the plus sign on the left specifies the size,InstalledAccording to general

  • Modify the constraints

    A:

    First Item: The First control constraint to set

    Second Item: The Second control constraint to be referenced

    Relation: The Relation between the first control and the second control constraint values

    • Less Than or Equal: Less than or equal to
    • EqualIs equal to:
    • Greater Than or Equal: Greater than or equal to

    Constraint: the offset of a Constraint

    Priority: indicates the Priority of the constraint

    • Required(1000) : default priority (high priority)
    • Required(1000) : indicates the medium priority
    • Required(1000) : indicates a low priority

    Multiplier: Multiplier of the constraint value

    • Reverse Multiplier: Reverse multiple (0.5 becomes 2, 4:3 becomes 3:4)
    • Convert to Decimal: Converts to the decimal system
    • Presets: preset value (you can also set the required multiple without the preset value, such as 0.5)
    • 1:1
    • 4:3:4:3
    • 16:9:16:9

    Placeholder (Remove at build time) : Remove this constraint at compile time

    Core formula: attribute of first Item =(<=/>=) attribute of second Item *Multiplier+Constant

    Method 2:

  • PreView (see device PreView via PreView)

Set in codeAutoLayout

usingNSLayoutConstraintClass to create concrete constraint objects
Add and delete constraint objects to the corresponding view
- (void)addConstraint:(NSLayoutConstraint *)constraint
- (void)addConstraints:(NSArray<__kindof NSLayoutConstraint *> *)constraints
- (void)removeConstraint:(NSLayoutConstraint *)constraint 
- (void)removeConstraints:(NSArray<__kindof NSLayoutConstraint *> *)constraints
Copy the code

Note:

  • 1. Disable the Autoresizing function and set the following properties of the control to NO

    testView.translatesAutoresizingMaskIntoConstraints = NO;
    Copy the code
  • 2. Before adding constraints, ensure that all related controls are on their parent controls

    [self.view addSubview:testView];
    Copy the code
  • 3. No more setting frame for view

  • Example:

    Code implementation:

     [self.view setBackgroundColor:[UIColor whiteColor]];
     UIView *redView = [[UIView alloc]init];
     redView.backgroundColor = [UIColor redColor];
     [self.view addSubview:redView];
     // Disable the Autoresizing function and set the following property of the control to NO
     redView.translatesAutoresizingMaskIntoConstraints = NO;
      
     
     /* + (instancetype)constraintWithItem:(id)view1 attribute:(NSLayoutAttribute)attr1 relatedBy:(NSLayoutRelation)relation toItem:(nullable id)view2 attribute:(NSLayoutAttribute)attr2 multiplier:(CGFloat)multiplier constant:(CGFloat)c View1: control to be constrained attr1: type to be constrained (top, bottom, left, right, etc.) Relation: relation to the reference control (less than or equal, equal, greater than or equal to) view2: reference control attr2: type to be constrained (top, bottom, left, right, etc.) Multiplier: multiplier of the constraint value c: offset */
    
      / / redView,10,300,100 (10)
      NSLayoutConstraint *xConstraint = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:10];
      [self.view addConstraint:xConstraint];
      
      NSLayoutConstraint *yConstraint = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:10];
      [self.view addConstraint:yConstraint];
    
      NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0 constant:300];
      [redView addConstraint:widthConstraint];
    
      NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0 constant:100];
      [redView addConstraint:heightConstraint];
    Copy the code

Common layout screen adaptation methods

  • Autoresizing
  • AutoLayou
  • VFL
  • Masonry
  • SnapKit