一群程序猿的秘密基地iOS学习iOS适配

Masonry

2016-06-10  本文已影响717人  i赵磊
《[一个程序猿的秘密基地](http://www.jianshu.com/collection/7b76c71b2d73?utm_campaign=maleskine&utm_content=collection&utm_medium=reader_share&utm_source=weibo)》专题
前言:本文章第一时间出现在一个程序猿的秘密基地专题中,如果您喜欢类似的文章,请您点击一个程序猿的秘密基地进行关注,在以后的日子里与小编共同成长!

·
·

不喜欢废话,用下面的代码给大家介绍下Masonry的用法,谢谢大家的此次捧场

/*
 这两个宏是Masonry框架提供的,存在于示例文件<Masonry iOS Examples-Prefix.pch>中
 第一个宏的作用:可以全程不用以'mas_'作为开头识别,可在项目中直接引出left、top、right、height……等属性
 第二个宏的作用:让equalTo具有自动包装功能,比如自动将20包装为@20(也就是基本类型变Number)
 不过这两个宏如果要引入工程,必须要写在导入Masonry.h的前面,切记、!
 */
//define this constant if you want to use Masonry without the 'mas_' prefix
#define MAS_SHORTHAND
//define this constant if you want to enable auto-boxing for default syntax
#define MAS_SHORTHAND_GLOBALS


#import "ViewController.h"
#import <Masonry.h>
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self demo1];
    [self demo2];
}
-(void)demo2{
    int offsetNumber=10;
    __weak typeof(self)weakSelf=self;
    UIView *myRedView=[self addViewWithColor:[UIColor redColor]];
    [myRedView makeConstraints:^(MASConstraintMaker *make) {
        //格式示意:myRedView的边界等于self.view的边界内缩10
        make.edges.equalTo(weakSelf.view).insets(UIEdgeInsetsMake(offsetNumber, offsetNumber, offsetNumber, offsetNumber));
    }];
}
-(void)demo1{
    int offsetNumber=10;
    __weak typeof(self)weakSelf=self;
    //添加Views
    UIView *greenView=[self addViewWithColor:[UIColor greenColor]];
    UIView *redView=[self addViewWithColor:[UIColor redColor]];
    UIView *blueView=[self addViewWithColor:[UIColor blueColor]];
    //添加约束
    [greenView makeConstraints:^(MASConstraintMaker *make) {
        //格式示意:greenView的左边等于self.view的左边再加上10
        make.left.equalTo(weakSelf.view.left).offset(offsetNumber);
        make.top.equalTo(weakSelf.view.top).offset(offsetNumber);
        make.right.equalTo(redView.left).offset(-offsetNumber);
        make.bottom.equalTo(greenView.top).offset(-offsetNumber);
        //greenView的大小等于redView的大小(括号里不写参数会默认 识别左边的参数自动进行赋值)
        make.size.equalTo(redView);
        make.height.equalTo(blueView.height);
    }];
    [redView makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view.top).offset(offsetNumber);
        make.right.equalTo(weakSelf.view.right).offset(-offsetNumber);
        make.bottom.equalTo(blueView.top).offset(-offsetNumber);
    }];
    [blueView makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view.left).offset(offsetNumber);
        make.right.equalTo(weakSelf.view.right).offset(-offsetNumber);
        make.bottom.equalTo(weakSelf.view.bottom).offset(-offsetNumber);
    }];
}
//抽离耦合进行封装
-(UIView *)addViewWithColor:(UIColor *)color{
    UIView *view=[[UIView alloc]init];
    view.backgroundColor=color;
    view.layer.borderWidth=2.f;
    [self.view addSubview:view];
    return view;
}
@end

demo1效果图 demo2效果图
上一篇下一篇

猜你喜欢

热点阅读