Matthew Gillingham
Matthew Gillingham

Reputation: 3429

convertRect:toView doesn't return expected window coordinates

Currently, I am trying to get the coordinates of a UIWebView. This webView is the subview a viewController's view. The viewController is contained inside of a UINavigationController. The status bar and the navigation bar are both on screen.

The orientation is portrait. The view has been presented modally.

With the height of status bar at 20 and the height of navigation bar at 44, I would expect the frame of the webView (in window coordinates) would have an origin at (0, 64) and a width of (320, 416).

However, when I run this line

CGRect frame = [webView.superview convertRect:webView.frame toView:nil];

I get an origin of (0, 0) and a width of (320, 416).

Any ideas what I need to do to get the correct origin I am expecting? Am I using this method incorrectly? Or are my expectations wrong for some reason?

Upvotes: 2

Views: 3856

Answers (1)

viggio24
viggio24

Reputation: 12366

This is quite strange intact. I did a test with a very basic application made of a window, a navigation controller, a view controller and a web view. All created programmatically. The code is the following and at the end I plot all view frames while at the end I plot the converted rect:


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.

    UIViewController *vc = [[UIViewController alloc] initWithNibName:nil bundle:nil];
    UIWebView *wv = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 416)];
    [wv loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"]]];
    [vc.view addSubview:wv];
    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:vc];
    self.window.rootViewController=nc;
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];

    NSLog(@"W: %@",NSStringFromCGRect(self.window.bounds));
    NSLog(@"NC: %@",NSStringFromCGRect(nc.view.frame));
    NSLog(@"VC: %@",NSStringFromCGRect(vc.view.frame));
    NSLog(@"WV: %@",NSStringFromCGRect(wv.frame));

    NSLog(@"WV->WIN: %@",NSStringFromCGRect([wv.superview convertRect:wv.frame toView:nil]));

    return YES;
}

The results are the following:

W: {{0, 0}, {320, 480}}
NC: {{0, 0}, {320, 480}}
VC: {{0, 0}, {320, 416}}
WV: {{0, 0}, {320, 416}}
WV->WIN: {{0, 64}, {320, 416}}

which are the one you were expecting. Probably you're doing some mistake in the way the views are placed in the hierarchy. Are you for example using Interface Builder and in such case can you check that you didn't put the wrong coordinates in the view positions?

Upvotes: 3

Related Questions