{"id":1262,"url":"https://github.com/SnapKit/Masonry","last_synced_at":"2025-07-30T20:33:03.210Z","repository":{"id":9638390,"uuid":"11570469","full_name":"SnapKit/Masonry","owner":"SnapKit","description":"Harness the power of AutoLayout NSLayoutConstraints with a simplified, chainable and expressive syntax. Supports iOS and OSX Auto Layout","archived":false,"fork":false,"pushed_at":"2023-04-13T18:23:56.000Z","size":767,"stargazers_count":18055,"open_issues_count":147,"forks_count":3147,"subscribers_count":710,"default_branch":"master","last_synced_at":"2024-10-29T11:13:54.363Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Objective-C","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/SnapKit.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2013-07-22T01:15:48.000Z","updated_at":"2024-10-28T13:20:15.000Z","dependencies_parsed_at":"2022-08-07T05:01:12.248Z","dependency_job_id":"0c80ce0c-770f-4632-8794-faa6db222711","html_url":"https://github.com/SnapKit/Masonry","commit_stats":{"total_commits":324,"total_committers":63,"mean_commits":5.142857142857143,"dds":0.5154320987654322,"last_synced_commit":"8bd77ea92bbe995e14c454f821200b222e5a8804"},"previous_names":["cloudkite/masonry"],"tags_count":29,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SnapKit%2FMasonry","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SnapKit%2FMasonry/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SnapKit%2FMasonry/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SnapKit%2FMasonry/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/SnapKit","download_url":"https://codeload.github.com/SnapKit/Masonry/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":227663041,"owners_count":17800711,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-01-05T20:15:42.461Z","updated_at":"2024-12-04T20:31:11.893Z","avatar_url":"https://github.com/SnapKit.png","language":"Objective-C","readme":"# Masonry [![Build Status](https://travis-ci.org/SnapKit/Masonry.svg?branch=master)](https://travis-ci.org/SnapKit/Masonry) [![Coverage Status](https://img.shields.io/coveralls/SnapKit/Masonry.svg?style=flat-square)](https://coveralls.io/r/SnapKit/Masonry) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) ![Pod Version](https://img.shields.io/cocoapods/v/Masonry.svg?style=flat)\n\n**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](https://github.com/SnapKit/SnapKit) as it provides better type safety with a simpler API.**\n\nMasonry 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.\nMasonry supports iOS and Mac OS X.\n\nFor examples take a look at the **Masonry iOS Examples** project in the Masonry workspace. You will need to run `pod install` after downloading.\n\n## What's wrong with NSLayoutConstraints?\n\nUnder 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.\nImagine a simple example in which you want to have a view fill its superview but inset by 10 pixels on every side\n```obj-c\nUIView *superview = self.view;\n\nUIView *view1 = [[UIView alloc] init];\nview1.translatesAutoresizingMaskIntoConstraints = NO;\nview1.backgroundColor = [UIColor greenColor];\n[superview addSubview:view1];\n\nUIEdgeInsets padding = UIEdgeInsetsMake(10, 10, 10, 10);\n\n[superview addConstraints:@[\n\n    //view1 constraints\n    [NSLayoutConstraint constraintWithItem:view1\n                                 attribute:NSLayoutAttributeTop\n                                 relatedBy:NSLayoutRelationEqual\n                                    toItem:superview\n                                 attribute:NSLayoutAttributeTop\n                                multiplier:1.0\n                                  constant:padding.top],\n\n    [NSLayoutConstraint constraintWithItem:view1\n                                 attribute:NSLayoutAttributeLeft\n                                 relatedBy:NSLayoutRelationEqual\n                                    toItem:superview\n                                 attribute:NSLayoutAttributeLeft\n                                multiplier:1.0\n                                  constant:padding.left],\n\n    [NSLayoutConstraint constraintWithItem:view1\n                                 attribute:NSLayoutAttributeBottom\n                                 relatedBy:NSLayoutRelationEqual\n                                    toItem:superview\n                                 attribute:NSLayoutAttributeBottom\n                                multiplier:1.0\n                                  constant:-padding.bottom],\n\n    [NSLayoutConstraint constraintWithItem:view1\n                                 attribute:NSLayoutAttributeRight\n                                 relatedBy:NSLayoutRelationEqual\n                                    toItem:superview\n                                 attribute:NSLayoutAttributeRight\n                                multiplier:1\n                                  constant:-padding.right],\n\n ]];\n```\nEven with such a simple example the code needed is quite verbose and quickly becomes unreadable when you have more than 2 or 3 views.\nAnother option is to use Visual Format Language (VFL), which is a bit less long winded.\nHowever the ASCII type syntax has its own pitfalls and its also a bit harder to animate as `NSLayoutConstraint constraintsWithVisualFormat:` returns an array.\n\n## Prepare to meet your Maker!\n\nHeres the same constraints created using MASConstraintMaker\n\n```obj-c\nUIEdgeInsets padding = UIEdgeInsetsMake(10, 10, 10, 10);\n\n[view1 mas_makeConstraints:^(MASConstraintMaker *make) {\n    make.top.equalTo(superview.mas_top).with.offset(padding.top); //with is an optional semantic filler\n    make.left.equalTo(superview.mas_left).with.offset(padding.left);\n    make.bottom.equalTo(superview.mas_bottom).with.offset(-padding.bottom);\n    make.right.equalTo(superview.mas_right).with.offset(-padding.right);\n}];\n```\nOr even shorter\n\n```obj-c\n[view1 mas_makeConstraints:^(MASConstraintMaker *make) {\n    make.edges.equalTo(superview).with.insets(padding);\n}];\n```\n\nAlso note in the first example we had to add the constraints to the superview `[superview addConstraints:...`.\nMasonry however will automagically add constraints to the appropriate view.\n\nMasonry will also call `view1.translatesAutoresizingMaskIntoConstraints = NO;` for you.\n\n## Not all things are created equal\n\n\u003e `.equalTo` equivalent to **NSLayoutRelationEqual**\n\n\u003e `.lessThanOrEqualTo` equivalent to **NSLayoutRelationLessThanOrEqual**\n\n\u003e `.greaterThanOrEqualTo` equivalent to **NSLayoutRelationGreaterThanOrEqual**\n\nThese three equality constraints accept one argument which can be any of the following:\n\n#### 1. MASViewAttribute\n\n```obj-c\nmake.centerX.lessThanOrEqualTo(view2.mas_left);\n```\n\nMASViewAttribute           |  NSLayoutAttribute\n-------------------------  |  --------------------------\nview.mas_left              |  NSLayoutAttributeLeft\nview.mas_right             |  NSLayoutAttributeRight\nview.mas_top               |  NSLayoutAttributeTop\nview.mas_bottom            |  NSLayoutAttributeBottom\nview.mas_leading           |  NSLayoutAttributeLeading\nview.mas_trailing          |  NSLayoutAttributeTrailing\nview.mas_width             |  NSLayoutAttributeWidth\nview.mas_height            |  NSLayoutAttributeHeight\nview.mas_centerX           |  NSLayoutAttributeCenterX\nview.mas_centerY           |  NSLayoutAttributeCenterY\nview.mas_baseline          |  NSLayoutAttributeBaseline\n\n#### 2. UIView/NSView\n\nif you want view.left to be greater than or equal to label.left :\n```obj-c\n//these two constraints are exactly the same\nmake.left.greaterThanOrEqualTo(label);\nmake.left.greaterThanOrEqualTo(label.mas_left);\n```\n\n#### 3. NSNumber\n\nAuto Layout allows width and height to be set to constant values.\nif you want to set view to have a minimum and maximum width you could pass a number to the equality blocks:\n```obj-c\n//width \u003e= 200 \u0026\u0026 width \u003c= 400\nmake.width.greaterThanOrEqualTo(@200);\nmake.width.lessThanOrEqualTo(@400)\n```\n\nHowever Auto Layout does not allow alignment attributes such as left, right, centerY etc to be set to constant values.\nSo if you pass a NSNumber for these attributes Masonry will turn these into constraints relative to the view\u0026rsquo;s superview ie:\n```obj-c\n//creates view.left = view.superview.left + 10\nmake.left.lessThanOrEqualTo(@10)\n```\n\nInstead of using NSNumber, you can use primitives and structs to build your constraints, like so:\n```obj-c\nmake.top.mas_equalTo(42);\nmake.height.mas_equalTo(20);\nmake.size.mas_equalTo(CGSizeMake(50, 100));\nmake.edges.mas_equalTo(UIEdgeInsetsMake(10, 0, 10, 0));\nmake.left.mas_equalTo(view).mas_offset(UIEdgeInsetsMake(10, 0, 10, 0));\n```\n\nBy default, macros which support [autoboxing](https://en.wikipedia.org/wiki/Autoboxing#Autoboxing) are prefixed with `mas_`. Unprefixed versions are available by defining `MAS_SHORTHAND_GLOBALS` before importing Masonry.\n\n#### 4. NSArray\n\nAn array of a mixture of any of the previous types\n```obj-c\nmake.height.equalTo(@[view1.mas_height, view2.mas_height]);\nmake.height.equalTo(@[view1, view2]);\nmake.left.equalTo(@[view1, @100, view3.right]);\n````\n\n## Learn to prioritize\n\n\u003e `.priority` allows you to specify an exact priority\n\n\u003e `.priorityHigh` equivalent to **UILayoutPriorityDefaultHigh**\n\n\u003e `.priorityMedium` is half way between high and low\n\n\u003e `.priorityLow` equivalent to **UILayoutPriorityDefaultLow**\n\nPriorities are can be tacked on to the end of a constraint chain like so:\n```obj-c\nmake.left.greaterThanOrEqualTo(label.mas_left).with.priorityLow();\n\nmake.top.equalTo(label.mas_top).with.priority(600);\n```\n\n## Composition, composition, composition\n\nMasonry also gives you a few convenience methods which create multiple constraints at the same time. These are called MASCompositeConstraints\n\n#### edges\n\n```obj-c\n// make top, left, bottom, right equal view2\nmake.edges.equalTo(view2);\n\n// make top = superview.top + 5, left = superview.left + 10,\n//      bottom = superview.bottom - 15, right = superview.right - 20\nmake.edges.equalTo(superview).insets(UIEdgeInsetsMake(5, 10, 15, 20))\n```\n\n#### size\n\n```obj-c\n// make width and height greater than or equal to titleLabel\nmake.size.greaterThanOrEqualTo(titleLabel)\n\n// make width = superview.width + 100, height = superview.height - 50\nmake.size.equalTo(superview).sizeOffset(CGSizeMake(100, -50))\n```\n\n#### center\n```obj-c\n// make centerX and centerY = button1\nmake.center.equalTo(button1)\n\n// make centerX = superview.centerX - 5, centerY = superview.centerY + 10\nmake.center.equalTo(superview).centerOffset(CGPointMake(-5, 10))\n```\n\nYou can chain view attributes for increased readability:\n\n```obj-c\n// All edges but the top should equal those of the superview\nmake.left.right.and.bottom.equalTo(superview);\nmake.top.equalTo(otherView);\n```\n\n## Hold on for dear life\n\nSometimes you need modify existing constraints in order to animate or remove/replace constraints.\nIn Masonry there are a few different approaches to updating constraints.\n\n#### 1. References\nYou 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.\nYou could also reference multiple constraints by storing them away in an array.\n\n```obj-c\n// in public/private interface\n@property (nonatomic, strong) MASConstraint *topConstraint;\n\n...\n\n// when making constraints\n[view1 mas_makeConstraints:^(MASConstraintMaker *make) {\n    self.topConstraint = make.top.equalTo(superview.mas_top).with.offset(padding.top);\n    make.left.equalTo(superview.mas_left).with.offset(padding.left);\n}];\n\n...\n// then later you can call\n[self.topConstraint uninstall];\n```\n\n#### 2. mas_updateConstraints\nAlternatively if you are only updating the constant value of the constraint you can use the convience method `mas_updateConstraints` instead of `mas_makeConstraints`\n\n```obj-c\n// this is Apple's recommended place for adding/updating constraints\n// this method can get called multiple times in response to setNeedsUpdateConstraints\n// which can be called by UIKit internally or in your code if you need to trigger an update to your constraints\n- (void)updateConstraints {\n    [self.growingButton mas_updateConstraints:^(MASConstraintMaker *make) {\n        make.center.equalTo(self);\n        make.width.equalTo(@(self.buttonSize.width)).priorityLow();\n        make.height.equalTo(@(self.buttonSize.height)).priorityLow();\n        make.width.lessThanOrEqualTo(self);\n        make.height.lessThanOrEqualTo(self);\n    }];\n\n    //according to apple super should be called at end of method\n    [super updateConstraints];\n}\n```\n\n### 3. mas_remakeConstraints\n`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.\n\n`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.\n\n```obj-c\n- (void)changeButtonPosition {\n    [self.button mas_remakeConstraints:^(MASConstraintMaker *make) {\n        make.size.equalTo(self.buttonSize);\n\n        if (topLeft) {\n        \tmake.top.and.left.offset(10);\n        } else {\n        \tmake.bottom.and.right.offset(-10);\n        }\n    }];\n}\n```\n\nYou can find more detailed examples of all three approaches in the **Masonry iOS Examples** project.\n\n## When the ^\u0026*!@ hits the fan!\n\nLaying 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:\n\n```obj-c\nUnable to simultaneously satisfy constraints.....blah blah blah....\n(\n    \"\u003cNSLayoutConstraint:0x7189ac0 V:[UILabel:0x7186980(\u003e=5000)]\u003e\",\n    \"\u003cNSAutoresizingMaskLayoutConstraint:0x839ea20 h=--\u0026 v=--\u0026 V:[MASExampleDebuggingView:0x7186560(416)]\u003e\",\n    \"\u003cNSLayoutConstraint:0x7189c70 UILabel:0x7186980.bottom == MASExampleDebuggingView:0x7186560.bottom - 10\u003e\",\n    \"\u003cNSLayoutConstraint:0x7189560 V:|-(1)-[UILabel:0x7186980]   (Names: '|':MASExampleDebuggingView:0x7186560 )\u003e\"\n)\n\nWill attempt to recover by breaking constraint\n\u003cNSLayoutConstraint:0x7189ac0 V:[UILabel:0x7186980(\u003e=5000)]\u003e\n```\n\nMasonry adds a category to NSLayoutConstraint which overrides the default implementation of `- (NSString *)description`.\nNow you can give meaningful names to views and constraints, and also easily pick out the constraints created by Masonry.\n\nwhich means your console output can now look like this:\n\n```obj-c\nUnable to simultaneously satisfy constraints......blah blah blah....\n(\n    \"\u003cNSAutoresizingMaskLayoutConstraint:0x8887740 MASExampleDebuggingView:superview.height == 416\u003e\",\n    \"\u003cMASLayoutConstraint:ConstantConstraint UILabel:messageLabel.height \u003e= 5000\u003e\",\n    \"\u003cMASLayoutConstraint:BottomConstraint UILabel:messageLabel.bottom == MASExampleDebuggingView:superview.bottom - 10\u003e\",\n    \"\u003cMASLayoutConstraint:ConflictingConstraint[0] UILabel:messageLabel.top == MASExampleDebuggingView:superview.top + 1\u003e\"\n)\n\nWill attempt to recover by breaking constraint\n\u003cMASLayoutConstraint:ConstantConstraint UILabel:messageLabel.height \u003e= 5000\u003e\n```\n\nFor an example of how to set this up take a look at the **Masonry iOS Examples** project in the Masonry workspace.\n\n## Where should I create my constraints?\n\n```objc\n@implementation DIYCustomView\n\n- (id)init {\n    self = [super init];\n    if (!self) return nil;\n\n    // --- Create your views here ---\n    self.button = [[UIButton alloc] init];\n\n    return self;\n}\n\n// tell UIKit that you are using AutoLayout\n+ (BOOL)requiresConstraintBasedLayout {\n    return YES;\n}\n\n// this is Apple's recommended place for adding/updating constraints\n- (void)updateConstraints {\n\n    // --- remake/update constraints here\n    [self.button remakeConstraints:^(MASConstraintMaker *make) {\n        make.width.equalTo(@(self.buttonSize.width));\n        make.height.equalTo(@(self.buttonSize.height));\n    }];\n    \n    //according to apple super should be called at end of method\n    [super updateConstraints];\n}\n\n- (void)didTapButton:(UIButton *)button {\n    // --- Do your changes ie change variables that affect your layout etc ---\n    self.buttonSize = CGSize(200, 200);\n\n    // tell constraints they need updating\n    [self setNeedsUpdateConstraints];\n}\n\n@end\n```\n\n## Installation\nUse the [orsome](http://www.youtube.com/watch?v=YaIZF8uUTtk) [CocoaPods](http://github.com/CocoaPods/CocoaPods).\n\nIn your Podfile\n\u003e`pod 'Masonry'`\n\nIf you want to use masonry without all those pesky 'mas_' prefixes. Add #define MAS_SHORTHAND to your prefix.pch before importing Masonry\n\u003e`#define MAS_SHORTHAND`\n\nGet busy Masoning\n\u003e`#import \"Masonry.h\"`\n\n## Code Snippets\n\nCopy the included code snippets to ``~/Library/Developer/Xcode/UserData/CodeSnippets`` to write your masonry blocks at lightning speed!\n\n`mas_make` -\u003e ` [\u003c#view#\u003e mas_makeConstraints:^(MASConstraintMaker *make) {\n     \u003c#code#\u003e\n }];`\n\n`mas_update` -\u003e ` [\u003c#view#\u003e mas_updateConstraints:^(MASConstraintMaker *make) {\n     \u003c#code#\u003e\n }];`\n\n`mas_remake` -\u003e ` [\u003c#view#\u003e mas_remakeConstraints:^(MASConstraintMaker *make) {\n     \u003c#code#\u003e\n }];`\n\n## Features\n* Not limited to subset of Auto Layout. Anything NSLayoutConstraint can do, Masonry can do too!\n* Great debug support, give your views and constraints meaningful names.\n* Constraints read like sentences.\n* No crazy macro magic. Masonry won't pollute the global namespace with macros.\n* Not string or dictionary based and hence you get compile time checking.\n\n## TODO\n* Eye candy\n* Mac example project\n* More tests and examples\n\n","funding_links":[],"categories":["Layout","框架和库","UI","Objective-C","Object-C 库","awesome-ios ##","UI Frameworks","[Objective-C](#objective-c)","Objective-C  Stars 1000以内排名整理","etc","iOS","9. 其他与展望","**Index**","Minor"],"sub_categories":["Other Hardware","Other free courses","Masonry-SnapKit","5. 参考材料","First, the gold standard libraries. The essentials --- You **NEED** to know about these !! You're likely to include a few of these in your own iOS projects","Auto Layout"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FSnapKit%2FMasonry","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FSnapKit%2FMasonry","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FSnapKit%2FMasonry/lists"}