views:

561

answers:

1

I've got a navigation controller based app that downloads an RSS feed and lays out the item titles in a TableView. That part works. When I click on an article title, I want to push an instance of my FeedArticleController onto the navigation stack. The FeedArticleController loadView method sets up the views (since I want to learn how to do this programmatically instead of using IB). Here's the loadView:

- (void)loadView {
    UIView *view = [[UIView alloc] init];
    self.view = view;

    webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    webView.delegate = self;

    [view addSubview:webView];
}

Does that make sense? Now, to make the webView actually load the page, I have this viewDiDLoad method:

- (void)viewDidLoad {
    [super viewDidLoad];
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"]]]; 
}

And then I have the delegate methods, webViewDidStartLoad and webViewDidFinishLoad. They just print to NSLog.

Am I missing something in how I constructed and added the views? The delegate methods seem to be printing to the log after a delay and there is traffic on the line when the webView is instantiated. So, I think it is loading the page, but not being displayed?

Thanks guys.

+1  A: 

There are two things to look into here:

  1. Setting the web view's autoresizingMask to UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight to make the web view resize when its parent is resized. This is because by default both the parent UIView you've created and the UIWebView have zeroed frames (0,0,0,0). By setting this, when the parent is resized prior to going onscreen the web view will be resized to match.
  2. Don't use a separate UIView instance, just set self.view to your UIWebView instance.

I'd recommend the second option, unless you really need another view inside your controller. Also, I should point out here that you're leaking both the UIView and the UIWebView inthe code snippet above. That might be simplified, but in case it isn't, you should release the views after assigning them. Here's an example implementing solution 2 above:

- (void) loadView
{
    webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    webView.delegate = self;    // weak reference: doesn't retain self
    self.view = webView;        // strong reference: retains webView
    [webView release];          // release initial reference: now 'owned' through self.view
}
Jim Dovey
Thanks for the comment. I'm not always sure if I should release the instance inside the method where it's made or in the dealloc methoc of the class.
Georges