Use constants for Masonry learning

;

Code using constants is simpler:

- (id)init {
    self = [super init];
    if (!self) return nil;

    UIView *purpleView = UIView.new;
    purpleView.backgroundColor = UIColor.purpleColor;
    purpleView.layer.borderColor = UIColor.blackColor.CGColor;
    purpleView.layer.borderWidth = 2;
    [self addSubview:purpleView];

    UIView *orangeView = UIView.new;
    orangeView.backgroundColor = UIColor.orangeColor;
    orangeView.layer.borderColor = UIColor.blackColor.CGColor;
    orangeView.layer.borderWidth = 2;
    [self addSubview:orangeView];

    //example of using constants

    [purpleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@20);
        make.left.equalTo(@20);
        make.bottom.equalTo(@-20);
        make.right.equalTo(@-20);
    }];

    // auto-boxing macros allow you to simply use scalars and structs, they will be wrapped automatically

    [orangeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(CGPointMake(0, 50));
        make.size.equalTo(CGSizeMake(200, 100));
    }];

    return self;
}

Run result:

In this case, I think that when the distance between the child view and the edge of the parent view is fixed, this can be done to further simplify the code, such as:

make.top.equalTo(@20);

Write completely should be:

make.top.equalTo(superview.top);

One detail to note is that the constant is preceded by an @ character.So no more?I remove the @ directly. I don't see any difference in the results, but it is obviously different. Follow up to see:

#define equalTo(...)                     mas_equalTo(__VA_ARGS__)
#define mas_equalTo(...)                 equalTo(MASBoxValue((__VA_ARGS__)))
#define MASBoxValue(value) _MASBoxValue(@encode(__typeof__((value))), (value))

Finally come to this function:

static inline id _MASBoxValue(const char *type, ...);

This function wraps a constant, converts it to a NSNumber or NSValue object, and that's all.

Posted by seeker2921 on Wed, 15 Jul 2020 09:21:28 -0700