根据设备方向,为什么我的子视图不能正确对中?
我试图创建一个自定义视图控制器的子视图中心在屏幕上。我成功了,当我导航到此视图时,居中视图出现在中心,并且在旋转设备时正确旋转。根据设备方向,为什么我的子视图不能正确对中?
但是,在这个导航应用,如果我输入自定义视图时不在纵向模式下,那么这应该为中心的观点确实在一个地方不在屏幕的中心位置本身。我已经把所有必要的autoresize属性放在视图,控制器,父母,祖母,圣洁处女身上......我已经用尽了一些东西来粘贴autoresize mask,而且这个例子看起来很糟糕。我敢肯定我错过了一些神奇的方法,它会解决一切,但我还没有想到要调用什么或在哪里(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,这种差异太大了。
我错过了什么让这些子视图居中正确进入景观模式的视图,并按照自动旋转?
看来,在其中一个横向取向loadView
中,控制器的视图原点设置为(0,20),这会将视图添加到屏幕后发生的旋转和自动调整混淆。奇怪的是,它在所有其他方向上都是(0,0)。
要解决该问题,添加这一行[super loadView]
后:
self.view.frame = self.view.bounds;
为了详细阐述:由于帧起源不是在(0,0),的self.view.center
概念在它正被上下文不正确用过的。 center
属性是在其超视图中可见的视图的中心。你真正想要的是视图的中心bounds
。
通过将视图框重置为视图边界,可以有效地将原点更改回(0,0),并且可以正确使用center
。
我决定在苹果的bug报告数据库中填写这个数据库,得到bug跟踪9187368。 – 2011-03-25 13:40:16
听起来不错。但是,请注意,如果视图托管在UIScrollView中,那么self.view.center也不起作用。最好将red_.center设置为'CGPointMake(self.view.bounds.size.width/2,self.view.bounds.size.height/2)'。 – Jason 2011-03-27 19:17:35