这个问题让我死了一个星期。我有完全相同的情况,也只想能够旋转一个视图。在选项卡式应用程序中绕过它的方法是注册方向通知。在 TabController(和任何其他超级视图)和要旋转的 VC 中为 shouldAutoRotate 返回 NO。然后在 viewWillAppear 中注册通知:
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:)name:UIDeviceOrientationDidChangeNotification
object:[UIDevice currentDevice]];
被调用的函数将如下所示:
- (void) orientationChanged:(NSNotification *)note
{
UIDevice * device = note.object;
switch(device.orientation)
{
case UIDeviceOrientationPortrait:
break;
case UIDeviceOrientationPortraitUpsideDown:
break;
case UIDeviceOrientationLandscapeLeft:
if(viewHasAppeared==true){
[self performSegueWithIdentifier:@"firstToLandscape" sender:self];}
break;
case UIDeviceOrientationLandscapeRight:
if(viewHasAppeared==true){
[self performSegueWithIdentifier:@"firstToLandscape" sender:self];}
break;
default:
break;
};
}
- 在 ViewDidAppear 中放置一个布尔值,因为在视图实际出现之前您无法继续。
现在,如果您在横向模式下更改为的视图不是选项卡式视图控制器,那么处理该问题的最佳方法是只允许在该视图中进行 AutoRotation,然后在 willAnimate 中您只需像这样关闭 VC:
-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
if(UIInterfaceOrientationIsPortrait(toInterfaceOrientation))
{
[self dismissViewControllerAnimated:YES completion:nil];
}
}
如果它是选项卡式视图,那么也只需在该视图中注册方向更改。但是,请确保在离开视图时删除orientationChange 通知。如果你不这样做,那么你也会从其他视图控制器中切换到横向。
当你离开去另一个选项卡时,你需要实现 tabBarController 委托,并确保你像这样删除观察者:
-(void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
if(![NSStringFromClass([viewController class])isEqualToString:@"FirstViewController"])
{
[[NSNotificationCenter defaultCenter]removeObserver:self name:UIDeviceOrientationDidChangeNotification object:[UIDevice currentDevice]];
}
}