O'Reilly logo

iPhone and iPad App 24-Hour Trainer by Gene Backlin, Abhishek Mishra

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

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.

UIButton

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

@interface ViewController : ...

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