iOS将会转向ToInterfaceOrientation正确的使用

我有一个非常简单的UIViewController,我想弄清楚如何使用willRotateToInterfaceOrientation。 我的UIViewController有一个非常简单的viewDidLoad方法:

-(void)viewDidLoad { [super viewDidLoad]; theBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 48.0f)]; theBar.tintColor = [UIColor orangeColor]; UINavigationItem *item = [[UINavigationItem alloc] initWithTitle:@"The Title"]; item.hidesBackButton = YES; [theBar pushNavigationItem:item animated:YES]; [item release]; [self.view addSubview:theBar]; } 

所以基本上,我只是在我的控制器的顶部有一个UINavigationBar。 而已。 根据我在网上find的内容,我实现了一些轮换的方法:

 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return YES; } -(void)willRotateToInterfaceOrientation: (UIInterfaceOrientation)orientation duration:(NSTimeInterval)duration { if ((orientation == UIInterfaceOrientationLandscapeLeft) || (orientation == UIInterfaceOrientationLandscapeRight)) { theBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 640, 48)]; } } 

因此,我以纵向模式启动应用程序,然后以横向模式扭曲。 基本上, theBar仍然是正常的大小,并没有得到调整。 我相信这是一个愚蠢的问题,但是使用旋转能力的正确方法是什么? 我想这样做,如果应用程序在横向模式下启动它也可以。 当UIViewController首次启动时,初始化组件的最佳方式是什么?请记住,我希望支持这两种方向,并且要记住,我希望能够根据整个持续时间中的方向更改来更改所有内容的大小UIViewController的生命? 谢谢!

你想要做的是改变现有的theBar对象的框架,而不是实例化一个新的。 你可以这样做:

 - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)orientation duration:(NSTimeInterval)duration { CGRect f = CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(theBar.frame); theBar.frame = f; } 

请注意,使用了self.view.frame的值,其中包含self.view.frame后的值。 另外请注意,我在这里使用的function是不同于你的。 我没有用你正在使用的函数testing它,所以我不能说这是否会起作用。 最后,你可以通过在viewDidLoad设置bar上的autoresizingmask来完全避免这种情况:

 [theBar setAutoresizingMask:UIViewAutoresizingFlexibleRightMargin];