我实例我UIView
实例中-viewDidLoad:
,并将其添加为子视图视图控制器的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:
中的键控动画,以便子视图更加优雅地从一个中心移动到另一个中心。但是现在,上面的这些对我来说很有用。