为什么我的子视图根据设备方向无法正确居中?

时间:2011-03-25 10:10:47

标签: iphone uiview uiviewcontroller rotation auto-rotation

我正在尝试以编程方式创建一个自定义视图控制器,其子视图位于屏幕中心。我成功了,当我导航到此视图时,居中的视图显示在中心,并在旋转设备时正确旋转。

但是,在这个导航应用程序中,如果我在纵向模式下时进入自定义视图,那么应该居中的视图会将自己定位在不是中心的位置屏幕。我已经将所有必要的自动调整属性放在视图,控制器,父级,祖母,神圣的处女......而且我已经用完了自动调整掩码的东西,而且示例看起来很糟糕。

我确定我错过了一个可以解决所有事情的神奇方法的调用,但我还没想到要调用什么或在哪里(setNeedsDisplay?setNeedsLayout?)。为了展示这个问题,我在https://github.com/gradha/iPhone-centered-rotation-test创建了一个完整的示例,您可以在模拟器或设备中克隆和运行该示例。我是从Apple的导航控制器创建的,只需添加一个假的单元格来推动我手动创建的视图。

可以在https://github.com/gradha/iPhone-centered-rotation-test/blob/master/Classes/CenteredViewController.m找到自定义视图,这是负责创建居中子视图的loadView方法:

/* Try to force the parent view to be as we want it. */
self.view.backgroundColor = [UIColor yellowColor];
self.view.autoresizesSubviews = YES;
self.view.autoresizingMask = UIViewAutoresizingFlexibleHeight |
    UIViewAutoresizingFlexibleWidth;

/* Top left blue square, for reference. */
blue_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 130, 130)];
[self.view addSubview:blue_];
blue_.backgroundColor = [UIColor blueColor];
[blue_ release];

/* Create red centered rectangle. */
red_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
red_.backgroundColor = [UIColor redColor];
red_.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin |
    UIViewAutoresizingFlexibleTopMargin |
    UIViewAutoresizingFlexibleLeftMargin |
UIViewAutoresizingFlexibleRightMargin;
red_.center = self.view.center;
[self.view addSubview:red_];
[red_ release];

Here's a link to a screen capture walkthrough of the application,首先进入纵向模式并旋转屏幕(正常工作),然后进入横向模式并旋转(取决于旋转方面,它看起来非常糟糕)。当您以横向模式进入视图时,根据方向,红色方块将具有196x34或140x34的左上角,这是一个太大的差异。

在横向模式下输入视图并按照自动旋转时,我缺少什么才能使这些子视图正确居中?

1 个答案:

答案 0 :(得分:8)

loadView中,在其中一个横向方向中,控制器的视图原点设置为(0,20),这会使视图添加到屏幕后发生的旋转和自动调整混乱。奇怪的是,它在所有其他方向都是(0,0)。

要解决此问题,请在[super loadView]之后添加此行:

self.view.frame = self.view.bounds;

详细说明:由于帧原点不在(0,0),因此self.view.center的概念在使用它的上下文中是不正确的。 center属性是该视图的中心,在其超级视图中可见。你真正想要的是视图的中心bounds

通过将视图框重置为视图的边界,可以有效地将原点更改回(0,0),并且可以正确使用center

相关问题