views:

946

answers:

1

Hi guys, I am a newbie at iPhone development and have a question, which may end up helping understand this concept in general.

Basically, I have UIViewController which loads up a view with a bunch of stuff. Now I want when a user clicks on a button, to load up a different view, which happens to be a webView. Now, I want the weview to load up a different url depending on which button was pressed in the original view.

how do i go about doing this? Basically in my head I thought i could load and swap the views when the button is pressed, like so:

In

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

    NSString *selectedLink = [valuesForSection objectAtIndex:row];

    NSString *urlAddress = @"http://www.google.com";

    //Create a URL object.
    NSURL *url = [NSURL URLWithString:urlAddress];

    //URL Requst Object
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

    //Load the request in the UIWebView.
    [webView loadRequest:requestObj];

    [self.view removeFromSuperview];
    [self.view insertSubview:webView atIndex:0];
}

Is this the right way of doing it? Or how do i go about doing this?

A: 

That would be the way I'd go about it, yes. Create a single UIWebView and, depending on which cell gets selected, load a NSURLRequest into the view using loadRequest:. It has the advantages of not requiring you to build separate web views for each cell, and of being asynchronous.

However, I wouldn't necessarily remove self.view from its superview whenever a cell gets clicked; rather, I'd pop up either a modal view controller (presentModalViewController:animated:) with the web view as its view, or I'd push a new controller onto a navigation controller stack (pushViewController:animated:). It's a smoother transition and will look better to the user.

Edit (in response to comment): Yes, it's better to have another controller than to just swap views. Doing removeFromSuperview and addSubview: keeps both views within the same controller, but as a result will make your code more difficult to manage (one controller will deal with two views) and have a worse user experience (there's no transition, like is built-in with a navigation controller push).

In order to do the push properly, you should:

  • Build a navigation controller for your existing view controller
  • When you need to, create a new instance of UIViewController with its view set to the UIWebView you create and load with your HTML
  • Push the new view controller onto the navigation controller stack from your old view controller by calling:
[self.navigationController pushViewController:newViewController animated:YES];
Tim
Could you tell me how you would implement pushviewcontroller? But having said that you are saying it would be better to have another controller rather than just a view within?
Doron Katz