Masonry的使用

Masonry是一个轻量级的布局框架 拥有自己的描述语法 采用更优雅的链式语法封装自动布局,简洁明了,并具有高可读性,而且同时支持 iOS 和 Max OS X。

如果使用系统带的NSLayoutConstraint代码量将非常大,同时还不好使用。

下面是使用源码链接 <a href="https://github.com/SnapKit/Masonry">Masonry源码</a>

1.居中显示

   UIView *sv = [UIView new];

    sv.backgroundColor = [UIColor greenColor];

    [self.view addSubview:sv];

    [sv mas_makeConstraints:^(MASConstraintMaker *make) {

        make.top.equalTo(@20);

        make.left.equalTo(@20);

        make.bottom.equalTo(@-20);

        make.right.equalTo(@-20);

    }];

 

2.设置视图并排

  UIView *view1 = [[UIView alloc] init];

    view1.backgroundColor = [UIColor redColor];

    [self.view addSubview:view1];

    

    UIView *view2 = [[UIView alloc] init];

    view2.backgroundColor = [UIColor yellowColor];

    [self.view addSubview:view2];

    

    

    int padding = 10;

    

    [view1 mas_makeConstraints:^(MASConstraintMaker *make) {

        

        // 设置其位于父视图的Y的中心位置

        make.centerY.mas_equalTo(self.view.mas_centerY);

        // 设置其左侧和父视图偏移10个像素

        make.left.equalTo(self.view).with.offset(padding);

        // 设置其右侧和view2偏移10个像素

        make.right.equalTo(view2.mas_left).with.offset(-padding);

        // 设置高度

        make.height.mas_equalTo(@120);

        // 设置其宽度

        make.width.equalTo(view2);

    }];

    

    [view2 mas_makeConstraints:^(MASConstraintMaker *make) {

        make.centerY.mas_equalTo(self.view.mas_centerY);

        make.left.equalTo(view1.mas_right).with.offset(padding);

        make.right.equalTo(self.view).with.offset(-padding);

        make.height.mas_equalTo(view1);

        make.width.equalTo(view1);

    }];

 

原文地址:https://www.cnblogs.com/menchao/p/4844632.html