views:

748

answers:

1

I have a simple UIViewController with just a UIWebView. The UIWebView should take all available space to show the content of an url.

I would like to reuse this ViewController in various places. In some cases it will be pushed into a NavigationController, in some it will be shown as a ModalViewController. Sometimes it might be inside a TabBarController. The size of the UIWebView will vary from case to case.

What's the best way to set the frame of the UIWebView without using the Interface Builder? In other words, how should I initialize webViewFrame in the following code? Or is there something else I'm missing?

- (void)viewDidLoad {
    [super viewDidLoad];
    UIWebView* webView = [[UIWebView alloc] initWithFrame:webViewFrame];
    webView.delegate = self;
    NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    [webView loadRequest:request];
    [self.view addSubview:webView];
    [webView release];
}

I have tried with different possibilities (self.view.frame, self.navigationController.view.frame, etc.), but nothing seems to work for all cases.

Thanks!

+2  A: 

If you're not using a NIB then what does your -loadView method look like? It should look like this:

- (void)loadView
{
    UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    webView.delegate = self;
    self.view = webView
    [webView release];
}

In this case, the initial frame is irrelevant. The UIViewController will take care of sizing your view correctly.

However, if you actually want to insert a web view (or any other view) into a parent view, you use autoresizeMask to control how your view resizes with its parent.

For example:

    UIView* parentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 200)];
    parentView.autoresizesSubviews = YES;

    UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

    [parentView addSubview:webView];
    self.view = parentView;
    [parentView release];

In this case, the webView's initial frame is relative to the parentView's bounds.

Darren
Thank you for the swift reply, Darren. Both options solve the question. However, there's something I don't understand. Why can't I use self.view.frame as webViewFrame in my code example? Shouldn't self.view.frame have the right size in viewDidLoad?
hgpc
self.view is resized after viewDidLoad. In fact, it can be resized at any time for a number of reasons (e.g., the call-in-progress title bar). Therefore, you must always set up your autoresizingMask so your sub-views are resized correctly.
Darren
Interesting. So there's actually no way to know the actual frame of the self.view in viewDidLoad, then?
hgpc