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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With