嗜酸性肉芽肿是什么病| me是什么基团| 孕早期吃什么| 快车和专车有什么区别| se是什么意思| 女人脚腿肿是什么原因| 肛裂是什么| 万圣节是什么时候| 约法三章什么意思| 长命锁一般由什么人送| 大便发绿色是什么原因| 烫伤挂什么科室| 全可以加什么偏旁| cp是什么单位| 吃什么长胖| 钾低会出现什么症状| 假正经是什么意思| 肾虚会导致什么| 卡西欧手表属于什么档次| 二网是什么意思| 苦杏仁味是什么中毒| 胃不舒服吃什么食物好| 猫什么时候打疫苗| 口苦是什么原因造成的| 6月26号是什么日子| 红色加绿色等于什么颜色| 心脏神经官能症吃什么药| 高血压高血糖能吃什么水果| 什么的什么是什么的伞| 1983属什么| 腰肌劳损用什么药| cashmere是什么面料| 春天是什么样子的| 梦见自己家盖房子是什么预兆| 龟头脱皮是什么原因| 量词是什么意思| 爷爷的妹妹叫什么| cma检测是什么| 心率快是什么原因| 女性私处长痘痘是什么原因| 木瓜什么味道| 大姨妈期间同房有什么影响| 喝酒不能吃什么药| 太多的理由太多的借口是什么歌| 什么是肾上腺素| 头晕做什么检查最准确| 依山傍水是什么意思| 八九不离十是什么意思| 脖子里面有结节是什么病| 鼻子痒用什么药好| 蓝营绿营什么意思| 气泡水是什么| 甲钴胺片主治什么病| 什么叫碳水化合物| 打哈欠是什么意思| 流量加油包是什么意思| 伟哥是什么意思| 八月八号什么星座| 骨钙素是什么| 空腹吃柿子有什么危害| 犹太人是什么意思| 大作是什么意思| 百合什么时候种| 3月1日是什么星座| 脑梗吃什么药好| 精神出轨什么意思| 重楼别名叫什么| 正月十九是什么日子| 肥猪拱门是什么生肖| 男人断眉有什么说法| a代表什么意思| 头昏脑胀是什么原因| 红红的什么| 什么是音色| 闻鸡起舞是什么意思| 蛋白粉适合什么人吃| 今年七夕节是什么时候| 降压药什么时候吃好| 嘴唇上长水泡是什么原因| 痛风什么引起的原因有哪些| 什么食物含硒| 胃部间质瘤是什么性质的瘤| 六月初十是什么日子| pe什么材质| 胆汁反流用什么药好| 千什么一发| 孕早期头晕是什么原因| 孕妇喝什么水好| 乳腺看什么科| 自渎是什么意思| spao是什么牌子| 高压偏低有什么危害| 中风的人吃什么好| 夜盲症是什么| 老师家访的目的是什么| 白茶泡出来是什么颜色| 女人什么时候是排卵期| 伊始什么意思| 找对象什么最重要| 白带什么味道| 男人什么时候精子最强| lh是什么意思啊| 甲状腺是什么症状| 什么叫业障| 苦甲水是什么| 宫颈息肉不切除有什么危害| 每天喝酸奶有什么好处和坏处| 什么食物养胃又治胃病| 头疼按什么穴位| 做梦怀孕了是什么意思| 黑眼圈看什么科| 什么是阳气| 古人的婚礼在什么时间举行| 低gi是什么意思| 珊瑚红是什么颜色| 痛点是什么意思| 人活着的意义是什么| 晚上睡不着是什么原因引起的| 两个月小猫吃什么食物| 什么叫盗汗| 陈皮的功效与作用主要治什么病| 蕊字五行属什么| 黑代表什么生肖| 毛孔粗大做什么医美| 吃什么补肾虚| 蛋白石是什么石头| 为什么放生泥鳅果报大| 肺栓塞是什么意思| 承上启下是什么意思| 过会是什么意思| 猫叫什么名字好听| 上当是什么意思| 什么是哺乳动物| 什么的花瓣| 月经颜色发黑是什么原因| 类风湿是什么病| 卵巢过度刺激综合症是什么| 异质性是什么意思| 生不如死是什么生肖| 肌筋膜炎吃什么药| 69年属什么生肖| 女汉子什么意思| 答非所问是什么意思| 好朋友是什么意思| 双鱼座和什么星座最配| 大学校长是什么级别| 糍粑是什么做的| 输血前八项指什么| 皮肤是什么组织| cm2是什么单位| 什么是阴历什么是阳历| 眉毛白是什么原因引起的| 色带是什么| 冠状沟是什么位置| 檀郎是什么意思| 刘备是什么样的人| ab型血为什么容易得精神病| 女性喝什么利尿最快| 脚趾甲变厚是什么原因| 美育是什么| 吃什么补骨髓造血| 澳门使用什么货币| cnc是什么牌子| 左边头痛什么原因| 一穷二白什么意思| 什么是前列腺炎| 金牛座跟什么星座最配| 梅毒长什么样| 鸡肾炒什么配菜好吃| 考号是什么| 农历六月十八是什么日子| 肠易激综合症什么症状| 便秘用什么药效果好| 尿蛋白两个加号是什么意思| 下蛊是什么意思| 什么是灌肠| 球蛋白适合什么人打| 查雌激素挂什么科| 此起彼伏是什么意思| 蜜蜡是什么东西| 用白醋泡脚有什么好处| 正常白带什么样| 舌头发白是什么原因| 大肠杆菌是什么意思| 意面是什么面| 公历是什么历| 膝关节疼痛用什么药效果最好| 梦到自己怀孕是什么意思| 外甥是什么意思| 宋朝之后是什么朝代| 好老公的标准是什么| 小儿咳嗽吃什么药好| 愣头青是什么意思| 为什么叫老鸨| 变异性哮喘咳嗽吃什么药| 合子是什么| 孙悟空头上戴的是什么| 本番是什么意思| 剂量是什么意思| zzegna是什么牌子价格| 什么游戏最赚钱| 10是什么意思| 总胆红素高是怎么回事有什么危害| 感冒吃什么恢复快| b站是什么| 无力感什么意思| 陕西有什么特产| 容易出汗是什么问题| 腹部包块是什么样子的| 什么汤降火| 舒筋健腰丸主治什么| 香蕉有什么功效和作用| 精神分裂吃什么药| 梦到牙齿掉了是什么意思| 50公斤发什么物流便宜| 二甲双胍不能和什么药一起吃| hcg什么时候开始下降| 合疗和医保有什么区别| 什么牌子的钙片好| 阄是什么意思| 苯磺酸氨氯地平片什么时候吃最好| 过什么不什么| 血小板计数偏高是什么意思| 虾吃什么| 掰弯了是什么意思| 什么茶降血糖| 提拉米苏是什么东西| 什么茶养胃| 黄瓜为什么会苦| 月经为什么来了一点又不来了| 怀孕初期吃什么蔬菜好| 汗液里面有什么成分| 昕字取名什么寓意| 颔是什么部位| 龙的三合生肖是什么| 头晕是什么毛病| 为什么尿是黄的| 发际线是什么| 浪子回头是什么意思| 开半挂车需要什么证| 戴尾戒是什么意思| 纤维化是什么意思| 舌头痒是什么原因| 宫内孕和宫外孕有什么区别| 掉睫毛是什么原因| 什么晚霜比较好用| 12345是什么投诉电话| 头伏二伏三伏吃什么| vape是什么意思| 乳腺结节吃什么食物好| 农垦局是什么性质单位| 什么是it行业| 脚心发痒是什么原因| 什么人不能吃黄精| 农历7月28日是什么星座| 脉搏强劲有力代表什么| ray是什么意思| 梦见数字是什么意思| 2000年为什么叫千禧年| 偏头痛什么原因| 认知什么意思| 实蛋是什么| 4月29号是什么星座的| 猫来家门口有什么预兆| 百度
Skip to content

Harness the power of AutoLayout NSLayoutConstraints with a simplified, chainable and expressive syntax. Supports iOS and OSX Auto Layout

License

Notifications You must be signed in to change notification settings

SnapKit/Masonry

Repository files navigation

Masonry Build Status Coverage Status Carthage compatible Pod Version

Masonry is still actively maintained, we are committed to fixing bugs and merging good quality PRs from the wider community. However if you're using Swift in your project, we recommend using SnapKit as it provides better type safety with a simpler API.

Masonry is a light-weight layout framework which wraps AutoLayout with a nicer syntax. Masonry has its own layout DSL which provides a chainable way of describing your NSLayoutConstraints which results in layout code that is more concise and readable. Masonry supports iOS and Mac OS X.

For examples take a look at the Masonry iOS Examples project in the Masonry workspace. You will need to run pod install after downloading.

What's wrong with NSLayoutConstraints?

Under the hood Auto Layout is a powerful and flexible way of organising and laying out your views. However creating constraints from code is verbose and not very descriptive. Imagine a simple example in which you want to have a view fill its superview but inset by 10 pixels on every side

UIView *superview = self.view;

UIView *view1 = [[UIView alloc] init];
view1.translatesAutoresizingMaskIntoConstraints = NO;
view1.backgroundColor = [UIColor greenColor];
[superview addSubview:view1];

UIEdgeInsets padding = UIEdgeInsetsMake(10, 10, 10, 10);

[superview addConstraints:@[

    //view1 constraints
    [NSLayoutConstraint constraintWithItem:view1
                                 attribute:NSLayoutAttributeTop
                                 relatedBy:NSLayoutRelationEqual
                                    toItem:superview
                                 attribute:NSLayoutAttributeTop
                                multiplier:1.0
                                  constant:padding.top],

    [NSLayoutConstraint constraintWithItem:view1
                                 attribute:NSLayoutAttributeLeft
                                 relatedBy:NSLayoutRelationEqual
                                    toItem:superview
                                 attribute:NSLayoutAttributeLeft
                                multiplier:1.0
                                  constant:padding.left],

    [NSLayoutConstraint constraintWithItem:view1
                                 attribute:NSLayoutAttributeBottom
                                 relatedBy:NSLayoutRelationEqual
                                    toItem:superview
                                 attribute:NSLayoutAttributeBottom
                                multiplier:1.0
                                  constant:-padding.bottom],

    [NSLayoutConstraint constraintWithItem:view1
                                 attribute:NSLayoutAttributeRight
                                 relatedBy:NSLayoutRelationEqual
                                    toItem:superview
                                 attribute:NSLayoutAttributeRight
                                multiplier:1
                                  constant:-padding.right],

 ]];

Even with such a simple example the code needed is quite verbose and quickly becomes unreadable when you have more than 2 or 3 views. Another option is to use Visual Format Language (VFL), which is a bit less long winded. However the ASCII type syntax has its own pitfalls and its also a bit harder to animate as NSLayoutConstraint constraintsWithVisualFormat: returns an array.

Prepare to meet your Maker!

Heres the same constraints created using MASConstraintMaker

UIEdgeInsets padding = UIEdgeInsetsMake(10, 10, 10, 10);

[view1 mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(superview.mas_top).with.offset(padding.top); //with is an optional semantic filler
    make.left.equalTo(superview.mas_left).with.offset(padding.left);
    make.bottom.equalTo(superview.mas_bottom).with.offset(-padding.bottom);
    make.right.equalTo(superview.mas_right).with.offset(-padding.right);
}];

Or even shorter

[view1 mas_makeConstraints:^(MASConstraintMaker *make) {
    make.edges.equalTo(superview).with.insets(padding);
}];

Also note in the first example we had to add the constraints to the superview [superview addConstraints:.... Masonry however will automagically add constraints to the appropriate view.

Masonry will also call view1.translatesAutoresizingMaskIntoConstraints = NO; for you.

Not all things are created equal

.equalTo equivalent to NSLayoutRelationEqual

.lessThanOrEqualTo equivalent to NSLayoutRelationLessThanOrEqual

.greaterThanOrEqualTo equivalent to NSLayoutRelationGreaterThanOrEqual

These three equality constraints accept one argument which can be any of the following:

1. MASViewAttribute

make.centerX.lessThanOrEqualTo(view2.mas_left);
MASViewAttribute NSLayoutAttribute
view.mas_left NSLayoutAttributeLeft
view.mas_right NSLayoutAttributeRight
view.mas_top NSLayoutAttributeTop
view.mas_bottom NSLayoutAttributeBottom
view.mas_leading NSLayoutAttributeLeading
view.mas_trailing NSLayoutAttributeTrailing
view.mas_width NSLayoutAttributeWidth
view.mas_height NSLayoutAttributeHeight
view.mas_centerX NSLayoutAttributeCenterX
view.mas_centerY NSLayoutAttributeCenterY
view.mas_baseline NSLayoutAttributeBaseline

2. UIView/NSView

if you want view.left to be greater than or equal to label.left :

//these two constraints are exactly the same
make.left.greaterThanOrEqualTo(label);
make.left.greaterThanOrEqualTo(label.mas_left);

3. NSNumber

Auto Layout allows width and height to be set to constant values. if you want to set view to have a minimum and maximum width you could pass a number to the equality blocks:

//width >= 200 && width <= 400
make.width.greaterThanOrEqualTo(@200);
make.width.lessThanOrEqualTo(@400)

However Auto Layout does not allow alignment attributes such as left, right, centerY etc to be set to constant values. So if you pass a NSNumber for these attributes Masonry will turn these into constraints relative to the view’s superview ie:

//creates view.left = view.superview.left + 10
make.left.lessThanOrEqualTo(@10)

Instead of using NSNumber, you can use primitives and structs to build your constraints, like so:

make.top.mas_equalTo(42);
make.height.mas_equalTo(20);
make.size.mas_equalTo(CGSizeMake(50, 100));
make.edges.mas_equalTo(UIEdgeInsetsMake(10, 0, 10, 0));
make.left.mas_equalTo(view).mas_offset(UIEdgeInsetsMake(10, 0, 10, 0));

By default, macros which support autoboxing are prefixed with mas_. Unprefixed versions are available by defining MAS_SHORTHAND_GLOBALS before importing Masonry.

4. NSArray

An array of a mixture of any of the previous types

make.height.equalTo(@[view1.mas_height, view2.mas_height]);
make.height.equalTo(@[view1, view2]);
make.left.equalTo(@[view1, @100, view3.right]);

Learn to prioritize

.priority allows you to specify an exact priority

.priorityHigh equivalent to UILayoutPriorityDefaultHigh

.priorityMedium is half way between high and low

.priorityLow equivalent to UILayoutPriorityDefaultLow

Priorities are can be tacked on to the end of a constraint chain like so:

make.left.greaterThanOrEqualTo(label.mas_left).with.priorityLow();

make.top.equalTo(label.mas_top).with.priority(600);

Composition, composition, composition

Masonry also gives you a few convenience methods which create multiple constraints at the same time. These are called MASCompositeConstraints

edges

// make top, left, bottom, right equal view2
make.edges.equalTo(view2);

// make top = superview.top + 5, left = superview.left + 10,
//      bottom = superview.bottom - 15, right = superview.right - 20
make.edges.equalTo(superview).insets(UIEdgeInsetsMake(5, 10, 15, 20))

size

// make width and height greater than or equal to titleLabel
make.size.greaterThanOrEqualTo(titleLabel)

// make width = superview.width + 100, height = superview.height - 50
make.size.equalTo(superview).sizeOffset(CGSizeMake(100, -50))

center

// make centerX and centerY = button1
make.center.equalTo(button1)

// make centerX = superview.centerX - 5, centerY = superview.centerY + 10
make.center.equalTo(superview).centerOffset(CGPointMake(-5, 10))

You can chain view attributes for increased readability:

// All edges but the top should equal those of the superview
make.left.right.and.bottom.equalTo(superview);
make.top.equalTo(otherView);

Hold on for dear life

Sometimes you need modify existing constraints in order to animate or remove/replace constraints. In Masonry there are a few different approaches to updating constraints.

1. References

You can hold on to a reference of a particular constraint by assigning the result of a constraint make expression to a local variable or a class property. You could also reference multiple constraints by storing them away in an array.

// in public/private interface
@property (nonatomic, strong) MASConstraint *topConstraint;

...

// when making constraints
[view1 mas_makeConstraints:^(MASConstraintMaker *make) {
    self.topConstraint = make.top.equalTo(superview.mas_top).with.offset(padding.top);
    make.left.equalTo(superview.mas_left).with.offset(padding.left);
}];

...
// then later you can call
[self.topConstraint uninstall];

2. mas_updateConstraints

Alternatively if you are only updating the constant value of the constraint you can use the convience method mas_updateConstraints instead of mas_makeConstraints

// this is Apple's recommended place for adding/updating constraints
// this method can get called multiple times in response to setNeedsUpdateConstraints
// which can be called by UIKit internally or in your code if you need to trigger an update to your constraints
- (void)updateConstraints {
    [self.growingButton mas_updateConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self);
        make.width.equalTo(@(self.buttonSize.width)).priorityLow();
        make.height.equalTo(@(self.buttonSize.height)).priorityLow();
        make.width.lessThanOrEqualTo(self);
        make.height.lessThanOrEqualTo(self);
    }];

    //according to apple super should be called at end of method
    [super updateConstraints];
}

3. mas_remakeConstraints

mas_updateConstraints is useful for updating a set of constraints, but doing anything beyond updating constant values can get exhausting. That's where mas_remakeConstraints comes in.

mas_remakeConstraints is similar to mas_updateConstraints, but instead of updating constant values, it will remove all of its constraints before installing them again. This lets you provide different constraints without having to keep around references to ones which you want to remove.

- (void)changeButtonPosition {
    [self.button mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(self.buttonSize);

        if (topLeft) {
        	make.top.and.left.offset(10);
        } else {
        	make.bottom.and.right.offset(-10);
        }
    }];
}

You can find more detailed examples of all three approaches in the Masonry iOS Examples project.

When the ^&*!@ hits the fan!

Laying out your views doesn't always goto plan. So when things literally go pear shaped, you don't want to be looking at console output like this:

Unable to simultaneously satisfy constraints.....blah blah blah....
(
    "<NSLayoutConstraint:0x7189ac0 V:[UILabel:0x7186980(>=5000)]>",
    "<NSAutoresizingMaskLayoutConstraint:0x839ea20 h=--& v=--& V:[MASExampleDebuggingView:0x7186560(416)]>",
    "<NSLayoutConstraint:0x7189c70 UILabel:0x7186980.bottom == MASExampleDebuggingView:0x7186560.bottom - 10>",
    "<NSLayoutConstraint:0x7189560 V:|-(1)-[UILabel:0x7186980]   (Names: '|':MASExampleDebuggingView:0x7186560 )>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x7189ac0 V:[UILabel:0x7186980(>=5000)]>

Masonry adds a category to NSLayoutConstraint which overrides the default implementation of - (NSString *)description. Now you can give meaningful names to views and constraints, and also easily pick out the constraints created by Masonry.

which means your console output can now look like this:

Unable to simultaneously satisfy constraints......blah blah blah....
(
    "<NSAutoresizingMaskLayoutConstraint:0x8887740 MASExampleDebuggingView:superview.height == 416>",
    "<MASLayoutConstraint:ConstantConstraint UILabel:messageLabel.height >= 5000>",
    "<MASLayoutConstraint:BottomConstraint UILabel:messageLabel.bottom == MASExampleDebuggingView:superview.bottom - 10>",
    "<MASLayoutConstraint:ConflictingConstraint[0] UILabel:messageLabel.top == MASExampleDebuggingView:superview.top + 1>"
)

Will attempt to recover by breaking constraint
<MASLayoutConstraint:ConstantConstraint UILabel:messageLabel.height >= 5000>

For an example of how to set this up take a look at the Masonry iOS Examples project in the Masonry workspace.

Where should I create my constraints?

@implementation DIYCustomView

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

    // --- Create your views here ---
    self.button = [[UIButton alloc] init];

    return self;
}

// tell UIKit that you are using AutoLayout
+ (BOOL)requiresConstraintBasedLayout {
    return YES;
}

// this is Apple's recommended place for adding/updating constraints
- (void)updateConstraints {

    // --- remake/update constraints here
    [self.button remakeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(self.buttonSize.width));
        make.height.equalTo(@(self.buttonSize.height));
    }];
    
    //according to apple super should be called at end of method
    [super updateConstraints];
}

- (void)didTapButton:(UIButton *)button {
    // --- Do your changes ie change variables that affect your layout etc ---
    self.buttonSize = CGSize(200, 200);

    // tell constraints they need updating
    [self setNeedsUpdateConstraints];
}

@end

Installation

Use the orsome CocoaPods.

In your Podfile

pod 'Masonry'

If you want to use masonry without all those pesky 'mas_' prefixes. Add #define MAS_SHORTHAND to your prefix.pch before importing Masonry

#define MAS_SHORTHAND

Get busy Masoning

#import "Masonry.h"

Code Snippets

Copy the included code snippets to ~/Library/Developer/Xcode/UserData/CodeSnippets to write your masonry blocks at lightning speed!

mas_make -> [<#view#> mas_makeConstraints:^(MASConstraintMaker *make) { <#code#> }];

mas_update -> [<#view#> mas_updateConstraints:^(MASConstraintMaker *make) { <#code#> }];

mas_remake -> [<#view#> mas_remakeConstraints:^(MASConstraintMaker *make) { <#code#> }];

Features

  • Not limited to subset of Auto Layout. Anything NSLayoutConstraint can do, Masonry can do too!
  • Great debug support, give your views and constraints meaningful names.
  • Constraints read like sentences.
  • No crazy macro magic. Masonry won't pollute the global namespace with macros.
  • Not string or dictionary based and hence you get compile time checking.

TODO

  • Eye candy
  • Mac example project
  • More tests and examples

About

Harness the power of AutoLayout NSLayoutConstraints with a simplified, chainable and expressive syntax. Supports iOS and OSX Auto Layout

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 50

什么水果最有营养 海字五行属什么 燕窝是补什么的 1975年是什么命 什么然而生
女性私处长痘痘是什么原因 花红是什么意思 第一次查怀孕挂什么科 高脂血症是什么病 育红班是什么意思
梦到和男朋友分手是什么征兆 白咖啡是什么 今日冲什么生肖 丑是什么意思 青蛙怕什么
宇宙外面是什么 肌电图挂什么科 女人梦见桃子预示什么 厦门有什么区 虾和什么不能一起吃
血糖高去医院挂什么科qingzhougame.com 上海的市花是什么hcv9jop5ns0r.cn 白酒是什么时候出现的hcv7jop7ns1r.cn 骨折后吃什么好的快wzqsfys.com 猫靠什么散热hcv9jop3ns3r.cn
鱼腥草有什么作用hcv8jop7ns6r.cn 功名是什么意思hcv8jop1ns1r.cn 金脸银脸代表什么人物hcv9jop6ns8r.cn 腿抽筋挂什么科室ff14chat.com 缺维生素a吃什么食物hcv8jop2ns8r.cn
茱萸是什么植物kuyehao.com 交尾是什么意思hcv9jop2ns1r.cn 91年什么命hcv8jop9ns6r.cn 三月二十是什么星座hcv7jop6ns8r.cn 处男是什么意思hcv7jop9ns8r.cn
什么去疤痕效果最好hcv9jop5ns9r.cn 囟门是什么xianpinbao.com 喝中药为什么会拉肚子hcv8jop7ns4r.cn 四个木字念什么hcv9jop0ns4r.cn 南京有什么好吃的hcv7jop9ns9r.cn
百度