为什么我的视图在interfaceOrientation更改时没有正确定位?

时间:2010-12-10 14:46:36

标签: cocoa-touch ipad orientation

我有一个UIViewController,其中有一个UIWebView。我希望UIWebView能够以横向和纵向模式放置在iPad屏幕的中央。所以,我已经像这样实现了它

// UIViewController
// InfoGraphicView is the UIWebView

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return YES;
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation 
                                duration:(NSTimeInterval)duration {
    if (toInterfaceOrientation == UIInterfaceOrientationPortrait ||
        toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
        [self layoutPortrait];
    } else {
        [self layoutLandscape];
    }
}

- (void)layoutLandscape {
    NSLog(@"Layout Landscape");
    infoGraphicView.frame = CGRectMake(100, 100, 936, 700);
}

- (void)layoutPortrait {
    NSLog(@"Layout Portrait");
    infoGraphicView.frame = CGRectMake(100, 100, 700, 936);
}

然而,它并没有像我预期的那样表现。在上面的代码中,我希望他的UIWebView是从顶部和左边100px(或点或任何单位)。但事实并非如此。在纵向模式下,它与屏幕的左上角齐平,而在横向模式下,它似乎在左上角部分位于屏幕外。

如果我将框架设置为CGRectMake(-100, 100, 700, 936),那么我会将其定位在屏幕中央,因为我希望它如此,但我不知道为什么。

像往常一样,我很容易忽视一些简单但我无法理解的事情。任何帮助一如既往地非常感谢。

2 个答案:

答案 0 :(得分:1)

这可能是Web视图所在的视图的问题。使用的坐标系是视图的superview的坐标系。如果该视图没有在旋转时调整大小,那么您将看到这样的意外布局。您可以通过superview属性访问视图的超级视图;查看其框架的一种方法是使用其描述。将此行放在您的一种布局方法中:

NSLog(@"Superview: %@", [infoGraphicView superview]);

那应该打印出视图的描述。

一旦弄明白,如果您希望Web视图具有相同的布局,则可以使用其autoresizingMask属性。如果你这样设置:

infoGraphicView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

然后视图将自动更改其宽度和高度,以保持顶部,左侧,右侧和底部边距相同。

答案 1 :(得分:1)

您在infoGraphicView上设置的坐标是相对于其超级视图的,而不是一般的屏幕。并且视图不一定会剪切他们的子视图。此外,自动设置为self.view的形状取决于Interface Builder中设置的缩放标记。但是,我认为默认设置为填满整个屏幕。

那就是说,我认为错误在于你使用了willRotateToInterfaceOrientation:duration:。这是在旋转开始之前调用的,因此self.view具有旧的大小(即,如果从纵向旋转到横向,它仍将是纵向大小,反之亦然)。可能更好地挂钩willAnimateRotationToInterfaceOrientation:duration: - 然后设置了正确的大小,你将在CoreAnimation块中,这样你的视图将作为旋转动画的一部分增长/缩小。

还要检查您在infoGraphicView上设置的调整大小标志。除了您所做的任何更改外,它们还会自动生效。所以你可能想要全部禁用它们。