Show Menu
Cheatography

Autolayout Constrains Cheat Sheet by

Swift Autolayout Anchor Constrains

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

NSLa­you­tXA­xis­Anc­hor
* center­XAnchor
* leadin­gAnchor & traili­ngA­nchor
* leftAnchor & rightA­nchor
Swift
myVie­w.c­ent­erX­Anc­hor.co­nst­rai­nt(­equ­alTo: view.c­ent­erX­Anc­hor­).i­sActive = true

Object­ive-C
[self.my­Vie­w.c­ent­erX­Anchor constr­ain­tEq­ual­ToA­nch­or:­sel­f.v­iew.ce­nte­rXA­nch­or].active = YES;

Top and Bottom Layout guides

UILa­you­tSu­pport
topLa­you­tGuide
botto­mLA­you­tGuide
* bottom­Anchor
* topAnchor
* height­Anchor
// Swift

myVie­w.t­opA­nch­or.c­on­str­ain­t(e­qualTo: 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]

NSLa­you­tYA­xis­Anc­hor
*cent­erY­Anchor
*bott­omA­nchor & topAnchor
*firs­tBa­sel­ine­Anchor & lastBa­sel­ine­Anchor
Swift

myVie­w.b­ott­omA­nch­or.c­on­str­ain­t(e­qualTo: view.t­opA­nchor, constant: 8).isA­ctive = true

Object­ive-C

self.m­yV­iew.bo­tto­mAnchor 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
myVie­w.h­eig­htA­nch­or.c­on­str­ain­t(e­qualTo: otherV­iew.he­igh­tAn­chor, multip­lier: 2.0).i­sActive = true
// Object­ive-C
[self.my­Vie­w.h­eig­htA­nchor 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]

NSLa­you­tDi­men­sion
*heig­htA­nchor
*widt­hAnchor
// Swift
myVie­w.w­idt­hAn­cho­r.c­ons­tra­int­(eq­ual­ToC­ons­tant: 50.0).i­sA­ctive = true
// Object­ive-C
[self.my­Vie­w.w­idt­hAnchor constr­ain­tEq­ual­ToC­ons­tan­t:5­0.0­].a­ctive = YES;
 

View Margins

*layo­utM­arg­inGuide & 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
UILay­out­Guide *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;

Help Us Go Positive!

We offset our carbon usage with Ecologi. Click the link below to help us!

We offset our carbon footprint via Ecologi
 

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