为什么我的视图无法在interfaceOrientation更改上正确定位?

问题描述:

我有一个UIViewController在其中一个UIWebView。我希望UIWebView以横向和纵向模式位于iPad屏幕的中心。所以,我已经这样实施了为什么我的视图无法在interfaceOrientation更改上正确定位?

// 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),那么我将它定位在屏幕的中心,因为我希望它是,但我不知道为什么。

像往常一样,最有可能的东西很简单,我忽略了,但我无法弄清楚。任何帮助一如既往非常感谢。

您在infoGraphicView上设置的坐标是相对于其超视图而不是屏幕的一般。而且视图不一定会限制他们的子视图。此外,自动设置为self.view的形状将取决于Interface Builder中设置的缩放标志。不过,我认为默认情况下它被设置为填满整个屏幕。

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

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

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

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

这应该打印出视图的说明。

一旦你明白了,如果你想让web视图具有相同的布局,你可以使用它的autoresizingMask属性。如果设置这样的:

infoGraphicView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; 

那么该视图会自动改变其宽度和高度,以保持顶部,左侧,右侧和底部边缘相同。