iphone view mechanics

Thu, Jul 9, 2009

How does the iPhone interact with your application? How does your nice UI get displayed and what does all that gubbins in the code mean? Read on…

iPhone development overview

When a user chooses to launch your application on their iPhone/iPod Touch, a chain of command is built up with UIApplication at the root of the hierarchy. UIApplication looks in your app’s Info.plist to see what xib file to load:

MainWindow Info.plist

from the above, we can see that the app’s UI starts with MainWindow.xib, whose File’s Owner is UIApplication:

MainWindow Files Owner

and the connection between UIApplication and your application is made via the App Delegate. UIApplication::delegate holds a reference to HelloWorld App Delegate:

http://farm4.static.flickr.com/3124/3703494143_45f841df2b.jpg?v=0

In this model, instead of subclassing UIApplication to handle your application events, you instead implement a UIApplicationDelegate which is injected into UIApplication and is called when events need handled. The main Window object is passed to the delegate in its window member and the view controller via its viewController member:

@interface HelloWorldAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
    HelloWorldViewController *viewController;
}
and when the main window is finished loading, UIApplication lets your delegate know via applicationDidFinishLaunching:
- (void)applicationDidFinishLaunching:(UIApplication *)application {
    [window addSubview:viewController.view];
    [window makeKeyAndVisible];
}
where your delegate makes use of the window and view controller passed to it from UIApplication. You can see the connections auto setup by Interface Builder:

MainWindow Connections

Where is the UI for your application though? That’s in HelloWorldViewController, which is in HelloWorldViewController.xib, where it holds a reference to the UI in its view member:

View Controller Files Owner

so you can get to it from your app delegate via viewController.view.

To add things to your UI you work with the View object in HelloWorldViewController:

IBOutlet to UI connection

UI to IBAction connection

wiring up IBOutlet objects in your code to UI objects in Interface Builder, for code -> UI communication and IBAction objects in your code to UI objects for events coming from the UI to your code. So when the user clicks on a button in the UI, UIApplication tells your app delegate that a button has been clicked from your View and your view controller interacts with the code you wrote to handle that event:

// View Controller -> UI
IBOutlet UILabel* helloTextLabel;
…
// UI -> View Controller
- (IBAction)sayHello:(id)sender {
  // View Controller -> UI
  helloTextLabel.text = @“Hello World!”;
}

comments powered by Disqus