Creating Layout Constraints Programmatically

You have seen how constraints can be created in Interface Builder, but they can also be added programmatically using the NSLayoutConstraint class. Above, you created the constraint pinning the left side of the scroll view the standard distance from the left side of its superview, the window’s content view, using the Add New Constraints popover in IB. You would create an equivalent constraint programmatically like this:

l​e​t​ ​s​c​r​o​l​l​V​i​e​w​:​ ​N​S​S​c​r​o​l​l​V​i​e​w​ ​=​ ​.​.​.​ l​e​t​ ​s​u​p​e​r​v​i​e​w​ ​=​ ​s​c​r​o​l​l​V​i​e​w​.​s​u​p​e​r​v​i​e​w​!​ l​e​t​ ​c​o​n​s​t​r​a​i​n​t​ ​=​ ​N​S​L​a​y​o​u​t​C​o​n​s​t​r​a​i​n​t​(​i​t​e​m​:​ ​s​c​r​o​l​l​V​i​e​w​,​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ...

Get Cocoa Programming for OS X: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.