ADDING VIEWS DYNAMICALLY USING CODE

Up to this point, all the UIs of your application have been created visually using Interface Builder. Although Interface Builder makes it relatively easy to build a UI using drag-and-drop, sometimes you are better off using code to create it. One such instance iswhen you need adynamic UI, such as for games.

image NOTE Interface Builder may be easy to use, but it can be confusing to some people. Because you often have more than one way of doing things in Interface Builder, it can create unnecessary complications. I know of developers who swear by creating their UIs using code.

In the following Try It Out, you learn how to create views dynamically from code, which will help you understand how views are constructed and manipulated.

TRY IT OUT: Creating Views from Code

image

  1. Using Xcode, create a Single View Application (iPhone) project and name it DynamicViews. You will also use the project name as the Class Prefix and ensure that you have the Use Automatic Reference Counting option unchecked.
  2. In the DynamicViewsViewController.m file, add the following statements that appear in bold:
    #import “DynamicViewsViewController.h”
    
    @implementation DynamicViewsViewController
    
    - (void)loadView {
        //---create a UIView object---
        UIView *view =
            [[UIView alloc] initWithFrame:[UIScreen ...

Get Beginning iOS 5 Application Development now with O’Reilly online learning.

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