teum
teum

Reputation: 125

change the content of a UIWebView from another Controller

I have a TableViewController which is supposed to load a ViewController with a WebView in it when I select a cell.

Here's the code :

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

    PostViewController *postViewController = [[PostViewController alloc] initWithNibName:@"PostViewController" bundle:[NSBundle mainBundle]];
    [postViewController.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.fr"]]]
    [self.navigationController pushViewController:postViewController animated:YES];

    [PostViewController release];

}

The problem is that the ViewController is loaded but nothing happens in the WebView. When I debug the program I can see that the WebView's address is 0x0 so I guess something's wrong. Is it because I try to modify the content of the WebView before its parent ViewController is loaded ?

I guess another way to do it properly would be to pass the URL to the ViewController and then to call loadRequest on the WebView from inside the viewWillAppear method. But I need to understand why it doesn't work this way.

Upvotes: 0

Views: 711

Answers (2)

ipraba
ipraba

Reputation: 16543

Try this

Instead of accessing the WebView why dont you just pass the URL value to the ViewController and load the Webview in the viewDidLoad of postViewController.

In your case

PostViewController *postViewController = [[PostViewController alloc] initWithNibName:@"PostViewController" bundle:[NSBundle mainBundle]];
postViewController.urlString = @"http://www.google.fr";
[self.navigationController pushViewController:postViewController animated:YES];

[PostViewController release];

In your postViewController.h declare the urlString with properties and synthesize in the .m file

Now in your viewDidLoad

//Alloc init your webview here
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];

Upvotes: 4

jnic
jnic

Reputation: 8785

0x0 is the address of nil, meaning that your web view has not been initialized at this point.

If you're creating your web view in the loadView or viewDidLoad methods of PostViewController, then calling setNeedsLayout immediately after initialization will force its creation:

PostViewController *postViewController = [[PostViewController alloc] init ...
[postViewController.view setNeedsLayout];

Otherwise, these methods will not be called until your view is displayed.

Upvotes: 2

Related Questions