views:

2134

answers:

0

I have a UIWebView in my app and I am having trouble making it work correctly simultaneously with landscape and the viewport zoom.

If I load pages in portrait and then rotate the phone, using the autoresize, it works correctly, zooming in for pages that are set to zoom. However, if I start the webview in landscape mode, I have to rotate to portrait and then rotate back to landscape to get the zoom correct. Mobile Safari does not have this problem.

For example if you load mobile.washingtonpost.com in the webview starting in landscape mode, the text is small. If you rotate to portrait and then back to landscape, the text is larger (as it should be). Mobile safari is smart enough to have the text large immediately when you load it in landscape. I want that :)

I have a workaround, but it is a total hack and I am wondering if there is a better way. Basically, I can get the landscape to have the right zoom, but only after it is loaded by twiddling the frame size of the webivew to 320 wide and then back to 480 wide. This gets me there, but: A) It seems silly, B) I can't do it until the page is loaded so you see the fonts resize.

Below you can see code for a very simple app that does this. It is easiest to use this in the simulator by setting the initial orientation to landscape by adding this to the info.plist: UIInterfaceOrientation UIInterfaceOrientationLandscapeRight

And here is the code:

// webviewAppDelegate.m

#import "webviewAppDelegate.h"

@implementation webviewAppDelegate

@synthesize window;

UIWebView *wv;

-(void) doWebView {
wv = [[UIWebView alloc] init];
wv.frame = CGRectMake(0,0,480,300);

[self.view addSubview:wv];

NSURLRequest *r = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://mobile.washingtonpost.com"]];
wv.delegate = self;
[wv loadRequest:r];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {

// HACK
wv.frame = CGRectMake(0,0,320,300);
wv.frame = CGRectMake(0,0,480,300);
}

- (void)applicationDidFinishLaunching:(UIApplication *)application {   

    // Override point for customization after application launch
    [window makeKeyAndVisible];

UIView *blank = [[UIView alloc] init];
self.view = blank;
[window addSubview:self.view];

NSTimer *t = [NSTimer timerWithTimeInterval : 2.0target: selfselector: @selector(doWebView) userInfo:nil repeats: NO];
[[NSRunLoop currentRunLoop] addTimer:t forMode:NSDefaultRunLoopMode];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {

returnYES;
}

- (void)dealloc {
    [window release];
    [super dealloc];
}


@end

--------------------------------------------------------

//  webviewAppDelegate.h

#import <UIKit/UIKit.h>

@interface webviewAppDelegate : UIViewController <UIApplicationDelegate, UIWebViewDelegate> {
    UIWindow *window;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;

@end