ios:Masonry

https://github.com/SnapKit/Masonry

pod 'Masonry'

- (void)viewDidLoad {
    [super viewDidLoad];

    // 使用 Masonry 布局,基本可以抛弃 CGRectMake 了,直接初始化即可。
    UIView *view = [[UIView alloc] init];

    view.backgroundColor = [UIColor darkGrayColor];

    // 在做布局之前,一定要先将 view 添加到 superview 上,否则会报错。
    [self.view addSubview:view];

    // mas_makeConstraints 就是 Masonry 的 autolayout 添加函数,将所需的约束添加到block中就行。
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        // 设置居中
        make.center.equalTo(self.view);
        // 设置宽度为200
        make.width.equalTo(@200);
        // 设置高度为200
        make.height.mas_equalTo(200);
    }];
}

//三个并排的view
- (void)viewDidLoad {
    [super viewDidLoad];

    // 初始化视图
    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];

    UIView *view3 = [[UIView alloc] init];
    view3.backgroundColor = [UIColor greenColor];
    [self.view addSubview:view3];

    // 布局视图
    [view1 mas_makeConstraints:^(MASConstraintMaker *make) {
        // 设置中心点
        make.centerY.mas_equalTo(self.view);
        // 设置左侧距离父视图10像素
        make.left.equalTo(self.view).offset(10);
        // 设置右侧距离和view2的左侧相距10像素
        make.right.equalTo(view2.mas_left).offset(-10);
        // 设置高度
        make.height.mas_equalTo(200);
        // 设置宽度和view2以及view3相等
        make.width.equalTo(@[view2, view3]);
    }];

    [view2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.view);
        make.height.mas_equalTo(view1);
        make.width.equalTo(@[view1, view3]);
    }];

    [view3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.view);
        make.left.equalTo(view2.mas_right).offset(10);
        make.right.equalTo(self.view).offset(-10);
        make.height.mas_equalTo(view1);
        make.width.equalTo(@[view1, view2]);
    }];

}

Masonry 的注意项

1、使用mas_makeConstraints方法的元素必须事先添加到父元素的中,例如:[self.view addSubview:view];

2、mas_equalTo和equalTo区别:mas_equalTo比equalTo多了类型转换操作,一般来说,大多数时候两个方法都是通用的,但是对于数值元素使用mas_equalTo。对于对象或是多个属性的处理,使用equalTo。特别是多个属性时,必须使用equalTo,例如:make.left.and.right.equalTo(self.view);。

3、注意方法with和and,这两个方法其实没有做任何操作,方法只是返回对象本身,这个方法的左右完全是为了方法写的时候的可读性 ,如下两行代码是完全一样的,但是明显加了and方法的语句可读 性更高点。

1.设置间距后用offset添加偏移量
make.left.equalTo(self.view.mas_left).offset(0);

2.设置宽的比例
make.width.equalTo(self.view.mas_width).multipliedBy(0.5)

3.设置参照的视图等宽高
make.width.and.height.equalTo(self.imageView);

4.设置内边距
make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(10, 10, 10, 10));

猜你喜欢

转载自samson870830.iteye.com/blog/2378165