Chapter 17

Creating UI Elements Programmatically

In previous lessons you learned how to use several standard user-interface objects, including buttons, image views, and labels. Using one of these objects in your application typically involves using Interface Builder to drag and drop instances onto a scene and then creating appropriate outlets/actions with the assistant editor.

However, there is another way to instantiate these objects, one that does not involve using the Interface Builder or assistant editor at all. Instead this alternate technique involves instantiating user-interface objects through Objective-C code. Any UIKit-based object that is instantiated with Interface Builder can also be instantiated programmatically.

Either method is fine; the one you choose is purely a matter of preference. Most likely, you will use the Interface Builder technique, but sometimes you may come across some code written by another programmer that creates user-interface elements programmatically. In these situations knowing how user-interface elements are created with code will be to your advantage.

Keep in mind, though, that some UIKit classes like UIAlertView and UIActionSheet cannot be instantiated with Interface Builder at all. This lesson shows you how to instantiate a few common UIKit objects with Objective-C code.


To create a UIButton instance programmatically, you first declare an appropriate UIButton* property in your view controller class:

@interface ViewController : ...

Get iPhone and iPad App 24-Hour Trainer now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.