This is part of an ELC Tech Network

iPhone Programming Tutorial – Transitioning Between Views

This tutorial will focus on transitioning from one view to another. We will be utilizing Apple’s UINavigationController. I will be using the code from the “Hello World” tutorial that I previously wrote. So if you have not completed it yet, go ahead and do it and come back to this page. (It’s quick I promise). You can view it here.

In this tutorial you will learn:

The first thing we are going to do is change our “Hello World” text to say something that sounds more like navigation. Go ahead and open RootViewController.m. Location the cellForRowAtIndexPath method (it’s the one that you edited to display “Hello World” in the table cell.

Change the line: [cell setText:@"Hello World"] ; to [cell setText:@"Next View"];

Add A New View

We will now add the view that we will be transitioning to. Click on RootViewController.xib and this should open up Interface Builder. We don’t actually need to edit this file. Once inside Interface Builder click on File -> New and select View.

It will add a blank View to your project. For now, we will keep it simple. Go ahead and drag a new Label on to the View. Double click on the label and change the text to whatever you want. I set mine to View 2 (I know, not very imaginative).

Let’s save the view. Click File -> Save. Call it View2. Make sure that you save it inside your Hello World project’s directory. It may want to save it somewhere else by default.

Next, you will see a screen asking you if you want to add the View to your project. Check the box next to Hello World and click Add.

Close Interface Builder. Drag the View2.xib file into the Resources folder, if it didn’t appear there by default (this will help maintain organization).

Add A View Controller

Now we need to create a ViewController class. This class will be used to connect the view that we just created to our code. Inside of Xcode click File -> New File… Select UIViewController subclass and click Next.

Name it View2ViewController and make sure “Also create “View2ViewController.h” “ is checked. Click Finish to continue. This will add the new ViewController to your project.

For organization sake, drag your View2ViewController.h and .m files into the Classes folder if they didn’t appear there to begin with.

Set Up The Transition To The New View

Open up RootViewController.h and add the following code:

This code should be pretty self explanatory, but I will explain it anyway. The import statement #import “View2ViewController.h” gets the header file of the ViewController that we created and allows us to create new instances of it.

Advertisement

Next, we declare a variable called view2ViewController which is of the type View2ViewController. One thing that I want to point out is the first part starts with a capitol “V” which is the type of object that we are declaring. The second part starts with a lower case “v“. This is our variable name that we will use to reference our ViewController object. Finally, we make our variable a property to set additional information.

Now, open up RootViewController.m and add the following code underneath @implementation RootViewController. This creates default “getter” and “setter” methods for our view2ViewController property.

Next find the function didSelectRowAtIndexPath. It may be commented out. If it is, go ahead and uncomment it. This method gets called (automatically) every time a table cell gets tapped. Notice that it takes an indexPath. This will be useful later on when I show you how to populate a UITableView with an NSArray. We will ignore it for now.

Add the following code to the method.

First we check to see if self.view2ViewController is null. This will happen the first time the user presses on the table cell. After this, the viewController gets stored in memory to optimize performance. Next we create a new instance of a View2ViewController and set it to our view2ViewController. Remember to pay attention to a capitol “V” verses a lowercase “v”. After we set this viewController to our viewController, it should be released. Remember, objective-c does not have a garbage collector, so we need to clear all of our unused objects from memory.

Finally, the last line of code is what actually transitions our view to the newly created view. The navigationController object is a stack that contains viewControllers. The view at the top of the stack is the one that gets rendered. So all we are doing is pushing a viewController onto this stack. There last part animated:YES, tells the compiler that we want an animated transition to the next view.

Connect The View To Code

Before this code will execute, we must connect the code that we just wrote to the view we just created. Double click on View2.xib to open it up in Interface Builder. We need to associate our View2ViewController class object with the view so click on the File’s Owner object and then click Tools -> Identity Inspector.

Click the dropdown next to class and select View2ViewController.

Next click anywhere on your view to select it. Click Tools -> Connections Inspector. Click in the circle next to New Referencing Outlet, drag it to the File’s Owner object and release it. The word view will popup. Go ahead and click on it.

Close Interface Builder. You can now click Build and Go. When you click on the words “Next View”, you will see the screen transition to your new view. There is still one thing missing. There is no back button in the NavigationController at the top. Apple actually adds this for us, but we need to set a title on our main view.

Adding The Back Button

Close the iPhone Simulator and open RootViewController.m. In the viewDidLoad method (gets called when the view is first loaded) add the following code.

Since RootViewController extends Apple’s class UITableViewController, it comes with a title property. You can set this to anything you want. I have set it to the string “Hello”. Now click Build and Go and you are done. Here are a few screenshots.

When you click on “Next View” it should transition to:

Notice the back button at the top with the text “Hello”. If you press it, your view will be popped from the NavigationController stack and the previous view will be shown. If you have any problems/questions/comments post them in the comments. I’m pretty good about answering them as it emails me when you do so and I receive them on my iPhone.  If you have any problems, you can download the source code here Hello World Views Source.  Happy iCoding!

This entry was posted in Interface Builder, iPhone Programming Tutorials and tagged , , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

165 Comments

  1. Balzidev
    Posted February 19, 2010 at 6:49 am | Permalink

    Thanks a lot. This is the best tutorial for iphone

  2. Balzidev
    Posted February 19, 2010 at 6:51 am | Permalink

    This is one of the best tutorial for iphone dev.

    Wanted to add some thing. If you get error about “@synthesize view2ViewController” not declared after your build and go then recheck your view2ViewController.h file again

    Balzi

  3. Posted February 22, 2010 at 10:21 am | Permalink

    Great simple yet effective tutorials. Keep up the good work!

  4. Konrad
    Posted March 3, 2010 at 2:27 pm | Permalink

    THERE’S A BUG (?)!
    Hi all. The problem is – when you click the Next View, then get to the View 2, and klick the back button (Hello), then you can’t repeat this action. The Next View row simply do nothing after that. Could someone tell me what i have to do to change this?

  5. Konrad
    Posted March 4, 2010 at 1:21 am | Permalink

    Nevermind, It’s working. Now could someone explain me how to add second row showing second view?

  6. fluvly
    Posted March 8, 2010 at 4:10 am | Permalink

    Brandon, just one question… why create a new view when a new xib file gets automatically added when you’re creating a new view controller class?

  7. Ryan
    Posted March 11, 2010 at 2:49 pm | Permalink

    I am new to iPhone programming and I am trying to figure out how to do the opposite of what you posted about.
    I want to start off with a view contoller and click a button on the screen and then it will show a TableView with a back button. Is that possible?

    Basically what I want to do is have a main screen that the user can enter search criteria and then the next page will bring up the search results in a long list. The user can think click on a row in the table that will take them to another UIView.

    UIView -> UITableView -> UIView

  8. ejaa
    Posted March 15, 2010 at 9:20 pm | Permalink

    how i can make many views.
    on thhis example, u just show only one view.
    i cant imagine how to do that
    thnks for advanced

  9. opéka
    Posted April 1, 2010 at 2:32 am | Permalink

    Thanks a lot, that was so useful for me :)

  10. Rahul
    Posted April 12, 2010 at 11:51 pm | Permalink

    hi, I tried the example starting with a ViewBasedApplication Template,Now I had following problems
    1) You did not show to include tany code in View2ViewController.m whereas the code that i downloaded had
    – (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
    this function so I added this to my controller.
    2) I used following code to trace the function calls
    NSLog(@”<<<<Entering %s <<<<<",__PRETTY_FUNCTION__);
    though it shows Entering and exit from -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    still the next view doesn't come up.

    Reply at ur ease

  11. spoolup
    Posted May 24, 2010 at 12:07 pm | Permalink

    great tut!
    how could it be modified so that when you go to the cell and press the next action is a uiwebview with a url (different url on every cell) with a back button?
    thanks

  12. Bivins
    Posted May 25, 2010 at 4:35 am | Permalink

    Thanks for this great tutorial .Please I have a question to ask as I am a newbie and would like to make an app where I have the multiple pages but my problem is that I do not know how to get read only text onto the pages or views. For instance if I want to get for example these italics paragraphs:

    “The iphone is a smart phone which has so many capabilities and functions. Its introduction haas open so many doors of opportunities to many developers who would otherwise have died and would have been buried without been known.
    Get the iPhone now and join the band wagon. Don’t be caught off guard. The world is moving so move with it .”

    of read only text onto view 2 above in your tutorial above. Please I will like to know the steps to take to get this done .
    Thanks a lot.

  13. Adel
    Posted July 24, 2010 at 3:15 pm | Permalink

    Your post solves a problem was irritating me for the whole day

    I didn’t set title for RootViewController so there was no back button.

    Thanks very much

  14. Shankar
    Posted August 26, 2010 at 7:47 am | Permalink

    Hi,
    first “Hello world” application run perfectly,even for navigation tutorial on click cell it navigate but second transition does not show.

    I get output on console is as follow:

    2010-08-26 19:14:49.989 Hello World[3473:207] *** Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘Could not load NIB in bundle: ‘NSBundle (loaded)’ with name ‘View2.”
    *** Call stack at first throw:
    (
    0 CoreFoundation 0×02393919 __exceptionPreprocess + 185
    1 libobjc.A.dylib 0x024e15de objc_exception_throw + 47
    2 CoreFoundation 0x0234c078 +[NSException raise:format:arguments:] + 136
    3 CoreFoundation 0x0234bfea +[NSException raise:format:] + 58
    4 UIKit 0x004a8af8 -[UINib instantiateWithOwner:options:] + 2024
    5 UIKit 0x004aa4b5 -[NSBundle(UINSBundleAdditions) loadNibNamed:owner:options:] + 168
    6 UIKit 0x00361fbb -[UIViewController _loadViewFromNibNamed:bundle:] + 70
    7 UIKit 0x0035fcd1 -[UIViewController loadView] + 120
    8 UIKit 0x004b6827 -[UITableViewController loadView] + 80
    9 UIKit 0x0035fbab -[UIViewController view] + 56
    10 UIKit 0x0035e050 -[UIViewController contentScrollView] + 42
    11 UIKit 0x0036ddf7 -[UINavigationController _computeAndApplyScrollContentInsetDeltaForViewController:] + 48
    12 UIKit 0x0036c4ff -[UINavigationController _layoutViewController:] + 43
    13 UIKit 0x0036d6c3 -[UINavigationController _startTransition:fromViewController:toViewController:] + 326
    14 UIKit 0×00368329 -[UINavigationController _startDeferredTransitionIfNeeded] + 266
    15 UIKit 0x0036f3a0 -[UINavigationController pushViewController:transition:forceImmediate:] + 876
    16 UIKit 0x003681c3 -[UINavigationController pushViewController:animated:] + 62
    17 Hello World 0×00002275 -[RootViewController tableView:didSelectRowAtIndexPath:] + 295
    18 UIKit 0×00329718 -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] + 1140
    19 UIKit 0x0031fffe -[UITableView _userSelectRowAtIndexPath:] + 219
    20 Foundation 0x00036cea __NSFireDelayedPerform + 441
    21 CoreFoundation 0x02374d43 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 19
    22 CoreFoundation 0×02376384 __CFRunLoopDoTimer + 1364
    23 CoreFoundation 0x022d2d09 __CFRunLoopRun + 1817
    24 CoreFoundation 0x022d2280 CFRunLoopRunSpecific + 208
    25 CoreFoundation 0x022d21a1 CFRunLoopRunInMode + 97
    26 GraphicsServices 0x02bf82c8 GSEventRunModal + 217
    27 GraphicsServices 0x02bf838d GSEventRun + 115
    28 UIKit 0x002c5b58 UIApplicationMain + 1160
    29 Hello World 0x00001db4 main + 102
    30 Hello World 0x00001d45 start + 53
    )
    terminate called after throwing an instance of ‘NSException’

    Pls help.

  15. Posted September 1, 2010 at 2:19 pm | Permalink

    terminate called after throwing an instance of ‘NSException’

    All your tutorials look great, however they seem old when using iOS4,
    Things like cell setText are deprecated now, and even more the app i write according to your howto/tutorial crashes when going to view2.

    Could you either way or fix these tutorials or write new up to date ones, because following yours when using iOS4 is very frustrating.

    other then that, great stuff man.

8 Trackbacks

  1. [...] iPhone Programming Tutorial – Transitioning Between Views [...]

  2. [...] iPhone Programming Tutorial – Transitioning Between Views Blogroll [...]

  3. [...] Transitioning Between Views [...]

  4. By links for 2008-10-27 | Nathan and his Open Ideals on October 27, 2008 at 10:04 am

    [...] iPhone Programming Tutorial – Transitioning Between Views | iCodeBlog This tutorial will focus on transitioning from one view to another. We will be utilizing Apple’s UINavigationController. (tags: iphone programming xcode tutorial) [...]

  5. By iPhone Developer resources | MikkoLehtinen.com on November 26, 2008 at 4:19 pm

    [...] iPhone Programming Tutorial – Transitioning Between Views [...]

  6. By Anil Anjan » iPhone Tutorial5–Views Transition on January 3, 2010 at 11:47 am

    [...] Set Up The Transition To The View [...]

  7. [...] Transitioning Between Views [...]

  8. By i-Tech » iPhone Tutorial5–Views Transition on February 20, 2010 at 11:54 am

    [...] iPhone Tutorial –Views Transitioning [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">