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!

Introduction of Masonry

MasonryIs a lightweight layout framework with its own descriptive syntax, wrapped in a more elegant chained syntaxAutoLayout, is concise and highly readable, and supports both iOS and Max OS X

Download linkMasonry


Masonry configuration

  • Using the Pods method to introduce the library,pod 'Masonry'
  • Importing header files#import "Masonry.h"

Masonry using

Example:

[testView mas_makeConstraints:^(MASConstraintMaker *make) {
        
     make.left.mas_equalTo(self.view.mas_left).offset(50);
     make.right.mas_equalTo(self.view.mas_right).offset(-50);           
     make.top.mas_equalTo(self.view.mas_top).offset(50);
     make.bottom.mas_equalTo(self.view.mas_bottom).offset(-50);
}];
Copy the code

Basic format 🙁make . Specify one of its attributes.Constraints)

make.attr.constrains
Copy the code

Make: Can be thought of as the agent of the view to be laid out

Constrains: the constraint may be a multi-level combination, such as a two-level combination of.mas_equalto (self.view.mas_left).offset(50), which displays the position to the left of the parent view and moves 50 points to the right (X axis)

Adds or updates constraints to controls

  • Adding a new constraint

    [xxxView mas_makeConstraints:^(MASConstraintMaker *make) {
         
      }];
    Copy the code
  • Delete all previous constraints on the control and add a new constraint

    [xxxView mas_remakeConstraints:^(MASConstraintMaker *make) {
          
      }];
    Copy the code
  • Update constraint, which one you write, update which one you write, and the other constraints stay the same

    [xxxView mas_updateConstraints:^(MASConstraintMaker *make) {
          
      }];
    Copy the code
To update constraint layout related apis, the following four apis are used: - (void) updateConstraintsIfNeeded this method is called, if there is a marked need to layout, the layout again immediately, internal will call updateConstraints method - (void) updateConstraints rewrite this method, Internal implementation process custom layout - (BOOL) needsUpdateConstraints whether the current need to layout, internal will determine whether the current constraints - (void) have marked setNeedsUpdateConstraints tags need to be relocatedCopy the code
There are three apis for rearranging UIViews: -(void)setNeedsLayout marked as needing relayout -(void)layoutIfNeeded To see if the current view is marked as needing relayout, -(void)layoutSubviews overwrites the current method and completes the layout internallyCopy the code

Setting constraints

The constraint relations instructions
equalTo()mas_equalTo() Sets the property to be equal to some numeric value
greaterThanOrEqualTo()mas_ greaterThanOrEqualTo() Sets the property to be greater than or equal to a certain value
lessThanOrEqualTo()mas_ lessThanOrEqualTo() Sets the property to be less than or equal to a certain value
multipliedBy()mas_ multipliedBy() Sets the value of the property multiplied by the factor
dividedBy()mas_ dividedBy() Sets the value of the property divided by the factor

Sets the control layout properties

The layout properties instructions
size width,height,size
margin left,top,right,bottom,leading,trailing
center center,centerX,centerY
The border edges
// I'll let you know what I'll let you know. // Constrain to margins @Property (nonatomic, strong, readonly) MASConstraint *leftMargin; // Constrain to margins @property (nonatomic, strong, readonly) MASConstraint *leftMargin; @property (nonatomic, strong, readonly) MASConstraint *rightMargin; @property (nonatomic, strong, readonly) MASConstraint *topMargin; @property (nonatomic, strong, readonly) MASConstraint *bottomMargin; @property (nonatomic, strong, readonly) MASConstraint *leadingMargin; @property (nonatomic, strong, readonly) MASConstraint *trailingMargin; @property (nonatomic, strong, readonly) MASConstraint *centerXWithinMargins; @property (nonatomic, strong, readonly) MASConstraint *centerYWithinMargins;Copy the code

Leading and left, trailing and right are normally equivalent, but are reversed when some layouts are right-to-left (such as in Arabic)

A comparison between mas_xxx and XXX

  • Take equalTo() and mas_equalTo() as examples

    #define mas_equalTo(...)                 equalTo(MASBoxValue((__VA_ARGS__)))
    #define mas_greaterThanOrEqualTo(...)      greaterThanOrEqualTo(MASBoxValue((__VA_ARGS__)))
    #define mas_lessThanOrEqualTo(...)       lessThanOrEqualTo(MASBoxValue((__VA_ARGS__)))
    
    #define mas_offset(...)                  valueOffset(MASBoxValue((__VA_ARGS__)))
    Copy the code
    • By default

    EqualTo () : In addition to NSNumber, there are CGPoint CGSize UIEdgeInsets mas_equalTo() : It does an Auto Boxing operation on its arguments, MASBoxValue(which is an NSValue or NSNumber object depending on the type of argument you pass in), and it’s not fussing about the arguments, it’s pretty much any data type you pass in

    • For object or multiple property processing, use equalTo. In particular, you must use equalTo for multiple attributes

    • Add the following macro (must precede #import “crops.h”)

      #define MAS_SHORTHAND_GLOBALS
      Copy the code

      Mas_equalTo can be prefixed without mas in code. There is no difference between mas_equalTo and equalTo

      [redView mas_makeConstraints:^(MASConstraintMaker *make) {
          make.width.equalTo(100);
          make.height.mas_equalTo(100);        
      }];
      Copy the code
  • Take width() and mas_width() as examples

    • By default width() : a property of a make object that adds a width constraint, indicating that width is constrained

    • Mas_width () : a property value, used as an equalTo argument, that represents the width property of a control

    • Add the following macro (must precede #import “crops.h”)

      #define MAS_SHORTHAND   
      Copy the code

      Mas_width can be left without mas prefix

      [redView mas_makeConstraints:^(MASConstraintMaker *make) {
       make.left.mas_equalTo(self.left).offset(10);
       make.top.mas_equalTo(self.top).offset(10);
       make.right.mas_equalTo(self.right).offset(-10);
       make.bottom.mas_equalTo(self.bottom).offset(-10);
      }];
      Copy the code

Set constraint migration

methods parameter instructions
offset(CGFloat offset) CGFloat How much the control property is offset relative to the reference
centerOffset(CGPoint offset) CGPoint controlscenterThe magnitude of the offset relative to the reference
sizeOffset(CGSize offset) CGSize controlssizeHow much offset relative to the reference
insets(MASEdgeInsets insets) MASEdgeInsets How much the edges of the control are offset relative to the reference

Offset the sample

[redView mas_makeConstraints:^(MASConstraintMaker *make) {
           make.left.mas_equalTo(self.mas_left).offset(20);
           make.top.mas_equalTo(self.mas_top).offset(20);
           make.right.mas_equalTo(self.mas_right).offset(-20);
           make.bottom.mas_equalTo(self.mas_bottom).offset(-20);
 }];
Copy the code

CenterOffset sample

[redView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(100);
        make.center.equalTo(self).centerOffset(CGPointMake(-100, -100));
 }];
Copy the code

SizeOffset sample

[redView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self);
        make.width.and.height.mas_equalTo(self).sizeOffset(CGSizeMake(-40, -40));
}];
Copy the code

Insets sample

// The specific parent control has a spacing of 20 around it
[redView mas_makeConstraints:^(MASConstraintMaker *make) {
       make.edges.mas_equalTo(self).insets(UIEdgeInsetsMake(20.20.20.20));
}];
Copy the code

Set the constraint priority

  • MasonryProvides us with three default methods,priorityLow(),priorityMedium(),priorityHigh(), the maximum value of the priority is 1000
     typedef UILayoutPriority MASLayoutPriority;
      static const MASLayoutPriority MASLayoutPriorityRequired = UILayoutPriorityRequired;
      static const MASLayoutPriority MASLayoutPriorityDefaultHigh = UILayoutPriorityDefaultHigh;
      static const MASLayoutPriority MASLayoutPriorityDefaultMedium = 500;
      static const MASLayoutPriority MASLayoutPriorityDefaultLow = UILayoutPriorityDefaultLow;
      static const MASLayoutPriority MASLayoutPriorityFittingSizeLevel = UILayoutPriorityFittingSizeLevel;
    Copy the code
  • You can set the value of the priority by yourselfpriority()Method to set
    [redView mas_makeConstraints:^(MASConstraintMaker *make) {
          
          make.center.mas_equalTo(self.view);
          make.width.mas_equalTo(100).priorityLow();
          make.width.mas_equalTo(50).priorityHigh();
          make.height.mas_equalTo(50).priority(200);
          make.height.mas_equalTo(100).priority(800);
      }];
    Copy the code

Set the constraint conjunction

With and and, in expressions, can be used as conjunctions to bring chained expressions closer to natural language

// Do nothing but return to yourself
  - (MASConstraint *)with {
    return self;
  }
  
  - (MASConstraint *)and {
    return self;
  }
Copy the code

Example: The following three sentences have the same effect

 make.width.width.height.equalTo(@100);
 make.width.and.height.equalTo(@100);
 make.width.height.equalTo(@100);
Copy the code

Masonry note

  • Before adding a constraint to the navigation, you need to add theaddSubviewYou can use it later, otherwise it will crash
  • When adding constraints, there are often two causes of constraint problems: constraint conflicts and lack of constraints. For both of these problems, you can debug and log

Common layout screen adaptation methods

  • Autoresizing
  • AutoLayou
  • VFL
  • Masonry
  • SnapKit