我在-viewDidLoad: 中实例化我的UIView 实例并将它们作为子视图添加到视图控制器的view 属性:
- (void) viewDidLoad {
[super viewDidLoad];
self.myView = [[[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 280.0f, 210.0f)] autorelease];
// ...
[self.view addSubview:myView];
}
然后我调用-viewWillAppear: 将这些子视图居中:
- (void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self adjustViewsForOrientation:[[UIDevice currentDevice] orientation]];
}
我也覆盖了-willRotateToInterfaceOrientation:duration:
- (void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)newInterfaceOrientation duration:(NSTimeInterval)duration {
[self adjustViewsForOrientation:newInterfaceOrientation];
}
-adjustViewsForOrientation: 方法根据设备的方向设置各种子视图对象的中心CGPoint:
- (void) adjustViewsForOrientation:(UIInterfaceOrientation)orientation {
if (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight) {
myView.center = CGPointMake(235.0f, 42.0f);
// ...
}
else if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown) {
myView.center = CGPointMake(160.0f, 52.0f);
// ...
}
}
加载视图控制器时,会根据设备的当前方向创建和定位UIView 实例。如果设备随后旋转,则视图将重新居中到新坐标。
为了使这更平滑,可以在-adjustViewsForOrientation: 中使用键控动画,以便子视图更优雅地从一个中心移动到另一个中心。但目前以上对我有用。