O'Reilly logo

Cocoa Programming for OS X: The Big Nerd Ranch Guide by Aaron Hillegass, Adam Preble, Nate Chandler

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Creating Views Programmatically

You will usually create your views in Interface Builder, but occasionally you will need to create views programmatically. If, for example, you have a pointer to a window and want to put a button on it, this code would create a button and put it on the window’s content view:

l​e​t​ ​s​u​p​e​r​v​i​e​w​ ​=​ ​w​i​n​d​o​w​.​c​o​n​t​e​n​t​V​i​e​w​
l​e​t​ ​f​r​a​m​e​ ​=​ ​N​S​R​e​c​t​(​x​:​ ​1​0​,​ ​y​:​ ​1​0​,​ ​w​i​d​t​h​:​ ​2​0​0​,​ ​h​e​i​g​h​t​:​ ​1​0​0​)​
l​e​t​ ​b​u​t​t​o​n​ ​=​ ​N​S​B​u​t​t​o​n​(​f​r​a​m​e​:​ ​f​r​a​m​e​)​
b​u​t​t​o​n​.​t​i​t​l​e​ ​=​ ​"​C​l​i​c​k​ ​m​e​!​"​
s​u​p​e​r​v​i​e​w​.​a​d​d​S​u​b​v​i​e​w​(​b​u​t​t​o​n​)​

Some of the Cocoa view classes are capable of a surprising variety ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required