iPad Programming Tutorial – Hello World++

April 5th, 2010 Posted by: brandontreb - posted under:Tutorials

Introduction

Now, that the iPad has been released, I’m sure you are all scrambling for ideas on how to snag a piece of the maket in the imminent gold rush.  iCodeBlog is going to help you on your journey with a series of iPad tutorials to come.

Since the iPad uses the same SDK as the iPhone, all of the code under the hood is almost identical.  Actually, when looking at the , you will realize that most of them are user interface related.  This is good news for us since we have already been coding iPhone.

While this tutorial is called “Hello World”, it is really much more than that.  I assume you already have working knowledge of iPhone/Objective-C programming.

What We Will Be Creating

In today’s tutorial, I will be showing you how to create an iPad project that uses the UISplitViewController to display content in 2 separate panes.  We will also be touching on some of the new design/UI patterns and giving an overall introduction to iPad programming.

The project will be based on one of my earliest tutorials that displayed a list of fruit in a UITableView and drilled down when they were selected.  We will be expanding on that example and creating something that will look like this.

It uses a UISplitViewController to display a UITableView on the left and a UIView with a UIImageView subview on the right.  This project is actually quite simple to create as the template code provides much of the code we need to get started.

Getting Started

1. Make sure you have downloaded the 3.2 SDK form .  The iPad simulator will come with this download.

2. Download the resources needed for this project and unzip them iPadHelloWorldResources.zip . (contains image files and a plist we will be using to load the images)

Creating The Project

Starting a project for the iPad is no different than starting one for the iPhone.  When you open XCode and select File->New Project, you should notice the addition of a Split View-Based Application.  Select this and name it iPadHelloWorld.

This will create a basic application with a UITableView on the left and a UIView on the right.  It will even populate the table with some sample elements.  It will add the following files to your project.

Here is a brief description of each of these files:

  • iPadHelloWorldAppDelegate – This is similar to every app delegate.  If you look in the application:didFinishLaunchingWithOptions method, you will see that the UISplitViewController is being allocated with the MasterViewController and DetailViewControllers.
  • MasterViewController – A UITableViewController, nothing fancy.  It will be handling the view on the left hand side.
  • DetailViewController – This handles the content view that you see on the right hand side.  We will be updating this as the user selects different rows in the table to the left.  This simply houses a single view.

Go ahead and press Build and Run to check out the application.  If you haven’t already done so, play around with the iPad contacts and settings apps as well.

Note: When you launch the application, you will only see the main view since the simulator runs in vertical mode.  To see the views side-by-side, rotate the simulator by clicking “Hardware -> Rotate Left/Right”.  You can also press CMD->Arrow Left/Right on the keyboard.

Importing The Project Images

Once you have had some time to play with the new iPad project, you will now need to import the images needed for this project.  After downloading and unzipping the files in from this tutorial, drag them into the project folder called “Resources-iPad”.

XCode will prompt you to copy the files, check yes and click OK.

Make sure you include all 4 images files as well as the file named fruits.plist.

Displaying The List Of Fruits

Displaying our fruits list is no different than displaying data in any other UITableView.  Let’s begin by opening MasterViewController.h and adding a declaration for our fruits array.

#import
 
@class DetailViewController;
 
@interface MasterViewController : UITableViewController {
    DetailViewController *detailViewController;
    NSArray * fruits;
}
 
@property (nonatomic, retain) IBOutlet DetailViewController *detailViewController;
@property (nonatomic, retain) NSMutableArray *fruits;
 
@end

As you can see, there is nothing new here.  We simply declare our fruits array and create a property for it.

We will be loading the fruits from the plist file that you imported into your project in the last step.  Loading content from a plist file is a very quick and easy solution when you don’t require a database.

Open up MasterViewController.m and add the following line of code to your viewDidLoad method.

- (void)viewDidLoad {
    [super viewDidLoad];
    self.fruits = [[NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"fruits" ofType:@"plist"]] retain];
}

The file fruits.plist is essentially an array that has been written out to a file.  If you open it up, it looks very similar to XML.  Now that our fruits array has been populated, let’s implement each of the UITableView delegate and datasource methods to populate the table.

UITableView datasource methods

- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [fruits count];
}
 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 
    static NSString *CellIdentifier = @"CellIdentifier";
 
        // Dequeue or create a cell of the appropriate type.
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
 
    // Get the object to display and set the value in the cell.
    cell.textLabel.text = [self.fruits objectAtIndex:indexPath.row];
    return cell;
}

Nothing special… We first tell the tableview that we want fruits.count (4 in this case) number of rows.

Next, we display the name of the fruit in each tableview cell.  If you want to learn more on UITableViews, read this tutorial.

UITableView delegate methods

- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 
    /*
     When a row is selected, set the detail view controller's detail item to the item associated with the selected row.
     */
    detailViewController.detailItem = [self.fruits objectAtIndex: indexPath.row];
}

Here, we are simply setting the detailItem property of the detailViewController to the selected fruit.  We will discuss this property later in this section, but for now all you need to know is that its type is id.

At this point, go ahead and press Build and Run to see your code in action.  You should see something that looks like this:

It displays the list of fruits, but nothing happens when you select a cell (well the title of the detailView may change).

Now that we have our list of fruits displayed, we now need to implement the code to display their corresponding image.

Displaying The Fruits

Displaying the selected fruit is actually quite simple.  The first thing we need to do is add a UIImageView to our detailView.

Start by adding the IBOutlet for the image view.  Open up DetailViewController.h and add the following code:

@interface DetailViewController : UIViewController  {
 
    UIPopoverController *popoverController;
    UINavigationBar *navigationBar;
 
    id detailItem;
 
    IBOutlet UIImageView * fruitImageView;
}
 
@property (nonatomic, retain) UIPopoverController *popoverController;
@property (nonatomic, retain) IBOutlet UINavigationBar *navigationBar;
 
@property (nonatomic, retain) id detailItem;
 
@property (nonatomic, retain) IBOutlet UIImageView * fruitImageView;
 
@end

All of the code here comes with the template except the code to add the IBOutlet UIImageView.  Once you have added this open up DetailView.xib in interface builder.

Add a UIImageView on to the view and size it to 500×500.

Now, click on the File’s Owner object and open the connection inspector (Tools -> connection inspector).

Drag from your imageView IBOutlet to the UIImageView and release.  The UIImageView is now connected to your outlet.

Note: If you want the images to not skew, set the content mode of the image view (in the attributes inspector) to Aspect Fit.

Now that the imageview has been connected, it’s time to write the code that updates it.  Close Interface Builder and open the file DetailViewController.m and add the following lines to the setDetailItem method:

- (void)setDetailItem:(id)newDetailItem {
    if (detailItem != newDetailItem) {
        [detailItem release];
        detailItem = [newDetailItem retain];
 
        // Update the view.
        navigationBar.topItem.title = detailItem;
        NSString * imageName = [NSString stringWithFormat:@"%@.png",detailItem];
        [self.fruitImageView setImage:[UIImage imageNamed:imageName]];
    }
 
    if (popoverController != nil) {
        [popoverController dismissPopoverAnimated:YES];
    }
}

Most of this code has been added by the template and I won’t discuss it too much in this tutorial.  But for now, the important additions are the lines that load the image based on  the name of the fruit and the one below it that sets the image property of the image view.

There you have it! Build and go and the application should function as mentioned.  Here is another screenshot of the final product.

Another Cool Feature Of SplitViewController

When in vertical mode, the SplitViewController gives you another new UI element called the UIPopOverView.  Collin will have a tutorial up soon on this view, but the figure below shows you what I’m talking about.

When the device is vertical, it will automatically rotate your view and provide a UIPopoverView when the “Master List” button is pretty. (BTW this button is also customizable).

You may download the source for this tutorial here iPadHelloWorld.zip.

If you have questions, post them here or .

Happy iCoding!

  • sgwbutcher

    Just out of curiosity, the iPhone 3.2 SDK download link has the following disclaimer:

    “iPhone SDK 3.2 beta is pre-release software and is considered Apple Confidential Information.”

    My understanding is that you aren’t to disclose such information.

  • http://www.prasannag.com Prasanna

    Thats awesome! Thanks a ton for this tutorial.

    I am porting my iPhone app to iPad now, and here is a question I have.

    In iPhone most text goes into a tableview. Is that the best way to do it in iPad as well? With such large screen, is it better to use it in text view? Is it easy enough to control the layout etc. ?

    Thanks again!

  • http://none sysco

    Yep,

    I think there’s NDA 3.2 now???

  • Konstantin

    Yep, there’s is NDA

  • MatthewF

    I appreciate the article, it was quite informative. All of this is under NDA right now, though, as noted by others. Perhaps you should pull the article until it’s lifted.

  • http://www.appstoremod.com Dewan Payroda

    Great tutorial!

  • jack

    great guide
    how would you make it so in the popover for the split view you could load your photo library?

  • http://yakshaving.net ash

    Hi there! Thanks for the tutorial.

    I tried to follow this but everytime I get through: self.fruits = [[NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@”fruits” ofType:@”plist”]] retain];

    I get an exception thrown. Any idea why?

    Thanks!
    Ash

  • http://brandontreb.com brandontreb

    @Ash, whats the exception? Sounds like the fruits.plist file hasn’t been copied to your project directory.

    @jack, that tut will come soon :)

  • branon

    Nice tut man..
    hey can you do one on using a splitView that have a view controller with icons that open up web pages on the detailed side?

  • http://yakshaving.net ash

    Whoops, sorry. N00b question, it wasn’t letting me include the @synthesize. I got it now and it’s working.

    Thanks!

  • http://www.iphone-geek.cn/%e7%bc%96%e7%a8%8b/ipad-%e7%bc%96%e7%a8%8b%e6%95%99%e7%a8%8b-hello-world iPhoneGeek 爱疯极客 » iPad 编程教程 – Hello World++

    [...] 原文见:iPad Programming Tutorial – Hello World++   用户界面, 编程   用户界面, 编程, iPad, 教程   [...]

  • Flo

    Great tutorial. It helped me a lot! But I have a question…

    I tried to group the fruits in the table view (MasterViewController). So I have the following entries:

    - Green fruits
    - Yellow fruits
    - Red fruits

    Tapping on one of those entries pushes another table view on the MasterViewController. I do it like this:

    - (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    RootViewController1 *controller = [[RootViewController1 alloc] initWithNibName:nil bundle:nil];

    [[self navigationController] pushViewController:controller animated:YES];
    }

    The new table view gets pushed on top of the other without a problem. But selecting an entry from there does not update the detail view. Logging the detailViewController.detailItem returns (null). Any idea how to fix this? Thanks in advance!

  • smaeung

    That is great tutorial for IPad. Thanks

    smaeung

  • http://www.moris.com Yakub_Moriss

    Nice work men…
    Do continue…
    Thanks for your great effort…

  • http://cananito.com/ Rogelio

    I think the beta and the current version changed some stuff… instead of MasterViewController, I have RootViewController. And in the DetailViewController.h, instead of navigationBar, I have toolBar, and I get an error if I try to do toolBar.topItem.title = …

    Anyone help? :D

  • pec1985

    how do I add a search bar on top to search for the items? (in this case, fruits)
    by the way, great tutorial

  • w.m.

    Hi, I’m new to SDK for iPad.
    I implemented UITableView delegate methods and pressed Build and Run.
    Application is not running and I get this warnings:

    warning: property ‘fruits’ requires method ‘-fruits’ to be defined – use @synthesize, @dynamic or provide a method implementation
    warning: property ‘fruits’ requires the method ‘setFruits:’ to be defined – use @synthesize, @dynamic or provide a method implementation

    Please, can you tell me what’s wrong?

  • w.m.

    I resolve my problem. In the first example of code in the file MasterViewController.h there has to be
    NSMutableArray * fruits;

    instead of
    NSArray * fruits;

    And in the file MasterViewController.m there has to be
    @synthesize fruits;

    I resolved my problem when I checked source for this tutorial.

    Thanks!

  • Sean

    I am using the 4.0 sdk where the toolbar is on the left and the nav bar is on the right. I changed it to have two nav bars but in portrait mode the popover button does not appear. Anyone know how to add the button to the nav bar ?

  • John

    RE: NSArray * fruits;

    Bingo! I tripped over the same thing. I added the @synthesize line (which isn’t in the tutorial either) and the debugger gave me that same error… sure enough, supposed to be a mutable array.

    -John

  • cybohemia

    Thanks for the tutorial! The iPad HIG encourages folks to add items to the toolbar and I was wondering if you can show us how to add a toolbar to the table side of the split UI. I can’t seem to find how to drag in a toolbar to that from the IB. Thanks!

  • Charlie

    Nice tutorial. How would I change the line below to display a web page instead of a picture?

    // Update the view.
    navigationBar.topItem.title = detailItem;
    NSString * imageName = [NSString stringWithFormat:@"%@.png",detailItem];
    [self.fruitImageView setImage:[UIImage imageNamed:imageName]];

  • sereal

    hi,
    Im using the latest SDK
    when I follow this tutorial, it seems like there’s some points I see it different on my XCode
    1. There’s no folder named “Resources-iPad” instead of “Resources”
    2. I can’t find MasterViewController on Classes Tree view instead of “RootViewController”

    and I get this Error

    warning: property ‘fruits’ requires method ‘-fruits’ to be defined – use @synthesize, @dynamic or provide a method implementation
    warning: property ‘fruits’ requires the method ’setFruits:’ to be defined – use @synthesize, @dynamic or provide a method implementation

    please advise

  • http://Twitter.com/Knodel_ Mike

    Hi! Thank you for the tutorial, but I can’t do one thing. In my app in the UITableView in the Root view I have a two-level table. The idea of the app is almost the same, but I can’t make the UIImageView change its content for a corresponding second-level table row selected. Please, help me

  • Aaron

    I got warnings about declaring fruitImageView and all that, so I just used this:

    fruitImageView.image = [UIImage imageNamed:imageName];

    instead of

    [self.fruitImageView setImage:[UIImage imageNamed:imageName]];

    It ends up matching the default code of setting the detailDescriptionLabel.text line, as a bonus.

  • http://codesketch.com/2010/05/ipad-hello-world-tutorial/ codesketch » Blog Archive » Getting Started Programing For the iPad

    [...] the full tutorial here. If you liked this article, Tweet it. We really would appreciate [...]

  • http://vaclav.vancura.org/weekly-digest-for-may-2nd Weekly Digest for May 2nd — Hello. My name is Václav Vančura.

    [...] iPad Programming Tutorial – Hello World++ | iCodeBlog [...]

  • http://www.fancypeople.org/?p=436 Programación en iPad: “Hello World” » Fancy People

    [...] (El presente artículo es una traducción y revisión libre del artículo publicado originalmente en icodeblog.com) [...]

  • Dan

    This is a great tutorial. How would I get it to display the pictures in a UIWebview instead of a UIIMageView? I want to be able to pinch and zoom…. ? I would appreciate any help.

  • ND

    Hey great tutorial! Really gives me a solid understanding of ipad development. One quick question though,

    How can i make it so the fruit image is scrollable? I tried putting UIImageView into a UIScrollView but im not sure what do do from there.

    This would be really helpful!

    Cheers

  • Ben

    Thanks for the tutorial.

    Unfortunately the code is truncated – I am viewing the page on my iPhone.

  • Andrew

    Great tut, off to buy my iPad now :) Is it possible to have the split view resizeable, with more than one column? What if i wanted 5 columsn, or my app had the ability to add a column or remove a column, would the split view be the way to go?

    Cheers. :)

  • http://www.coloradocomputerguy.com Alan

    Is anyone else having trouble with getting the NavigationBar Title to appear using the most current official SDK for 3.2? I get nothing and no errors. Did this method change? Thanks!! :)

  • nik

    Did you find a solution to this?
    Anyone?

  • Brad

    I keep getting an error when I try to include @synthesize fruits; What did you have to do?

  • http://fiveholiday55.blogspot.com Helen Dangote

    I was having problem getting the example to run, but I have figured it out now and everything works like a dream. Nice article.

  • Catherine

    It seems like this tutorial is missing the point to explain the code of application:applicationdidFinishLaunchingWithOptions method in iPadHelloWorldAppDelegate.m I could not make my app working after following this tutorial and I found that this code is missing in this method in my code.

    masterViewController = [[MasterViewController alloc] initWithStyle:UITableViewStylePlain];
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:masterViewController];

    detailViewController = [[DetailViewController alloc] initWithNibName:@”DetailView” bundle:nil];
    masterViewController.detailViewController = detailViewController;

    splitViewController = [[UISplitViewController alloc] init];
    splitViewController.viewControllers = [NSArray arrayWithObjects:navigationController, detailViewController, nil];
    splitViewController.delegate = detailViewController;

    I also found that many MACROs are different in my code. Is it because this tutorial is missing to explain that part or iPhone SDK 4.0 is upgraded and have different points from SDK 3.2?

    Thanks,

    ~ Catherine

  • newbie

    I’m looking for a split view tutorial that would use core data access and also have the ability to edit the data as well. Can you show this to us?

  • lola

    nice tut!

    what can i add in order to launch the split view with the first row selected in Master controller and the corresponding and his corresponding content displayed in detail view?

    Thanks!!

  • Nielsz

    You should change the NSArray to NSMutableArray *fruits;

  • Spoolup

    @Flo
    @Mike

    did you figure out how to get the detail view updated from the second viewcontroller?
    i’m stuck at the same spot…..

  • Lakshmi Anantharaman

    This is a great tutorial.

    I just want to point out two issues that I faced in case you copy and paste code like me :)

    @interface MasterViewController : UITableViewController {
    DetailViewController *detailViewController;
    NSArray * fruits;
    }

    @property (nonatomic, retain) IBOutlet DetailViewController *detailViewController;
    @property (nonatomic, retain) NSMutableArray *fruits;

    Please change the NSMutableArray to NSArray and this will allow you to add the @synthesize fruits; in the implementation file.

    Thanks
    Lakshmi