Show Menu
Cheatography

Autolayout Constrains Cheat Sheet by

Swift Autolayout Anchor Constrains

NSLayo­utX­Axi­sAnchor [Horiz­ontal]

NSLayo­utX­Axi­sAnchor
* center­XAnchor
* leadin­gAnchor & traili­ngA­nchor
* leftAnchor & rightA­nchor
Swift
myView.ce­nte­rXA­nch­or.c­on­str­ain­t(e­qualTo: view.c­ent­erX­Anc­hor­).i­sActive = true

Object­ive-C
[self.m­yV­iew.ce­nte­rXA­nchor constr­ain­tEq­ual­ToA­nch­or:­sel­f.v­iew.ce­nte­rXA­nch­or].active = YES;

Top and Bottom Layout guides

UILayo­utS­upport
topLay­out­Guide
bottom­LAy­out­Guide
* bottom­Anchor
* topAnchor
* height­Anchor
// Swift

myView.to­pAn­cho­r.c­ons­tra­int­(eq­ualTo: topLay­out­Gui­de.b­ot­tom­Anchor, constant: 8.0).i­sActive = true

// Object­ive-C
[self.s­ta­ckV­iew.to­pAnchor constr­ain­tEq­ual­ToA­nch­or:­sel­f.t­opL­ayo­utG­uid­e.b­ott­omA­nchor consta­nt:­8.0­].a­ctive = YES;
 

NSLayo­utY­Axi­sAnchor [Vertical]

NSLayo­utY­Axi­sAnchor
*cente­rYA­nchor
*botto­mAnchor & topAnchor
*first­Bas­eli­neA­nchor & lastBa­sel­ine­Anchor
Swift

myView.bo­tto­mAn­cho­r.c­ons­tra­int­(eq­ualTo: view.t­opA­nchor, constant: 8).isA­ctive = true

Object­ive-C

self.m­yVi­ew.b­ot­tom­Anchor constr­ain­tEq­ual­ToA­nch­or:­sel­f.v­iew.to­pAnchor consta­nt:­8.0­].a­ctive = YES

Example 2

 
Example to make the height of a view twice the height of another view with a multip­lier:
// Swift
myView.he­igh­tAn­cho­r.c­ons­tra­int­(eq­ualTo: otherV­iew.he­igh­tAn­chor, multip­lier: 2.0).i­sActive = true
// Object­ive-C
[self.m­yV­iew.he­igh­tAnchor constr­ain­tEq­ual­ToA­nch­or:­sel­f.o­the­rVi­ew.h­ei­ght­Anchor multip­lie­r:2.0].active = YES
 

NSLAyo­utD­ime­nsion [Size-­Based Constr­ains]

NSLayo­utD­ime­nsion
*heigh­tAnchor
*width­Anchor
// Swift
myView.wi­dth­Anc­hor.co­nst­rai­nt(­equ­alT­oCo­nstant: 50.0).i­sA­ctive = true
// Object­ive-C
[self.m­yV­iew.wi­dth­Anchor constr­ain­tEq­ual­ToC­ons­tan­t:5­0.0­].a­ctive = YES;
 

View Margins

*layou­tMa­rgi­nGuide & readab­leC­ont­ent­Guide
// Swift
let margins = view.l­ayo­utM­arg­ins­Guide myView.le­adi­ngA­nch­or.c­on­str­ain­t(e­qualTo: margin­s.l­ead­ing­Anc­hor­).i­sActive = true

// Object­ive-C
UILayo­utGuide *margins = self.v­iew.la­you­tMa­rgi­nsG­uide; [self.m­yV­iew.le­adi­ngA­nchor constr­ain­tEq­ual­ToA­nchor: margin­s.l­ead­ing­Anc­hor­].a­ctive = YES;
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          RxSwift Operators Cheat Sheet
            Swift Cheat Sheet by Rob Phillips