iOS Friday Followup: Programmatic Views

Although slightly late, this post is a summary of the programmatic method of adding views to our iOS projects.  While we’ve been working in IB up to this point, I felt that it would be well worth our time to write some code to see clearly what is happening when we drag views (labels, buttons, images, etc…) all willy-nilly out into our IB projects.

The first thing to keep in mind is that we started with a “Window-Based Application”, allowing us the freedom to set up our own classes from scratch as we saw fit.

Without getting into all the nitty-gritty details, here’s a brief snippet of code to add a view to a View Controller class programmatically:


UIView *theView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];

theView.backgroundColor = [UIColor blueColor];

self.view = theView;

The explanation:

On the first line, we are declaring and making a UIView called “theView”.  Using the [UIView alloc] command, we are setting up the view in memory.  the initWithFrame:CGRectMake means that we are creating the rectangular area (the frame) that will be the view.  The (0,0,320,480) are the coordinates of the rectangle starting with the x,y position of the rectangle on the screen (0,0 is top-left) and then the width and height of the rectangle.

The next line is pretty simple- it sets a background color for our newly created UIView.

And finally, self.view = theView tells our UIViewController class to make our newly created UIView the view for itself.

Simple, but possibly a bit confusing.  Just keep those steps in mind, and eventually, they’ll all begin to make more and more sense. :)

Happy coding!

One Response to iOS Friday Followup: Programmatic Views

  1. This is really helpful Chad. I looked at the snippet and realized that even though I remember doing this and it made sense at the time, the explanation is pretty necessary for me to understand it, so thanks.

Leave a Response