使用masonry手写约束

在iOS开发过程中,手写contraints是非常痛苦的一件事情,往往那么一丢丢功能要写大量的代码,非常容易发生错误,并且非常不方便调试。所以只有在不得以的情况下才采用手工方式写contraints,一般都在Storyboard中完成,但Storyboard也是一个坑爹的东东,特别是在SVN协作工作时各种问题不甚其烦;但是后来知道了Masonry,体验了一段时间,非常好用,自此很少再使用storyboard写UI了。

安装Masonry

安装使用Masonry的方式不止一种,但比较推荐的方式是使用CocoaPods来管理,具体的做法是在Podfile中添加一句pod 'Masonry',当然也可以指定版本:pod 'Masonry', '~> 0.6.1';对于Masonry这种第三方库,可能在任何页面中都会涉及到,所以最好在prefix pch文件中添加#import "Masonry.h",默认情况下,Masonry中的相关资源都有mas前缀,譬如mas_makeConstraints方法、mas_left属性等等,如果不想使用mas前缀,则可以在#import "Masonry.h"之前可以先定义一个宏#define MAS_SHORTHAND,但不推荐这样做,因为mas_left比left更不容易与其他的资源名称冲突。

Masonry常用技巧

同一行等比例显示多个view

UIView *redView = ({
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor redColor];
    view;
});
[self.view addSubview:redView];
    
UIView *yellowView = ({
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor yellowColor];
    view;
});
[self.view addSubview:yellowView];
    
UIEdgeInsets viewInsets = UIEdgeInsetsMake(100, 10, 0, 10);
    
[redView mas_makeConstraints:^(MASConstraintMaker *make) {
    UIView *superView = self.view;
    make.left.equalTo(superView).insets(viewInsets);
    make.right.equalTo(yellowView.mas_left).offset(-10);
    make.top.equalTo(superView).insets(viewInsets);
    make.width.equalTo(yellowView.mas_width).offset(0);
    make.height.equalTo(@100);
}];
    
[yellowView mas_makeConstraints:^(MASConstraintMaker *make) {
    UIView *superView = self.view;
    make.right.equalTo(superView).insets(viewInsets);
    make.left.equalTo(redView.mas_right).offset(10);
    make.top.equalTo(superView).insets(viewInsets);
    make.width.equalTo(redView.mas_width).offset(0);
    make.height.equalTo(@100);
}];

效果如下:

                        

原文地址:https://www.cnblogs.com/FightingLuoYin/p/4428074.html