Add a View to an iOS Application

Starting with an empty application, it's now necessary to add a view to the application.

The steps for adding the view are as follows:

  • From within the empty project, select File->New->File.
  • A dialog box will appear. Select iOS - Cocoa Touch in the leftmost area, and 'Objective-C class' in the rightmost area. Click Next.
  • A new dialog box will appear. Fill it out as follows:
  • Save the file. The view has now been created.

Once the view has been created, it's necessary to tell the main application to display the view. To do this, open GasCanManAppDelegate.m, add an import statement for the new view, and add the following code to the didFinishLaunchingWithOptions method:

  1. #import "GasCanManAppDelegate.h"
  2. #import "GasCanDetailViewController.h"
  3.  
  4. @implementation GasCanManAppDelegate
  5.  
  6. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  7. {
  8. self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
  9. // Override point for customization after application launch.
  10.  
  11. GasCanDetailViewController *baseView = [[GasCanDetailViewController alloc] init];
  12. [self.window setRootViewController:baseView];
  13.  
  14. self.window.backgroundColor = [UIColor whiteColor];
  15. [self.window makeKeyAndVisible];
  16. return YES;
  17. }

It's also necessary to add some controls to the view, so select the file named GasCanViewController.xib. A sample view should be displayed. Add Labels and Text Fields as shown below:


To add properties referencing the text fields, do the following:

  • Command-click on the file named GasCanDetailViewController.h, and it will open in a window next to the UI view.
  • Add brackets to the file to represent the area where properties are declared.
  • Right-click on each text field and drag a connection into the bracket area
  • A dialog box will appear. Fill it in as follows:

  • Once completed the following code should be in place:
  1. #import <UIKit/UIKit.h>
  2.  
  3. @interface GasCanDetailViewController : UIViewController {
  4.  
  5. __weak IBOutlet UITextField *name;
  6. __weak IBOutlet UITextField *level;
  7. __weak IBOutlet UITextField *size;
  8. }
  9.  
  10. @end

The last step is to actually have the view display the details of a GasCan object. For now, I'll simply hard-wire values by adding the following code to the viewDidLoad method within GasCanDetailViewController.m:

  1. - (void)viewDidLoad
  2. {
  3. [super viewDidLoad];
  4. // Do any additional setup after loading the view from its nib.
  5. [name setText:@"My Gas Can"];
  6. [level setText:@"2.5"];
  7. [size setText:@"5"];
  8. }

Once this is done, run the application, and you should see a screen similar to the following:

Next, I'll create a screen for managing multiple gas cans.