2016-01-10 45 views
0

我想在一个ViewController中禁用屏幕旋转。我用这个来改变屏幕方向为纵向:ObjC禁用ViewController旋转

-(void)viewDidAppear:(BOOL)animated{ 
    NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait]; 
    [[UIDevice currentDevice] setValue:value forKey:@"orientation"]; 
} 

,我禁用旋转这样的:

- (BOOL)shouldAutorotate{ 
    return NO; 
} 

- (UIInterfaceOrientationMask)supportedInterfaceOrientations{ 
    return UIInterfaceOrientationMaskPortrait; 
} 

-(NSUInteger)navigationControllerSupportedInterfaceOrientations:(UINavigationController *)navigationController { 
    return navigationController.topViewController.supportedInterfaceOrientations; 
} 

,但它不工作。它将屏幕旋转为纵向,但不会锁定它,如果我打开设备,它会改变屏幕方向。

+0

请访问我的答案[这里](http://stackoverflow.com/questions/34655338/how-can-i-rotate-a-uiviewcontroller-to-its-supported-interface-orientation-when/ 34655782#34655782) – Aamir

+0

它不起作用... – klh63917

+0

你可能错过了一些东西,我测试过这段代码,它对我来说工作正常。 – Aamir

回答

1

你可以试试这个代码:

-(BOOL)shouldAutorotate 
{ 
    return NO; 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation 
{ 
    return NO; 
} 

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation 
{ 
    return UIInterfaceOrientationPortrait; 
} 

上面的代码将只能与UIViewControllers不UINavigationController的栈工作。如果你正在使用一个UINavigationController你应该做到以下几点:

解决方案1:

  1. 添加到AppDelegate.h一个变量:@property (nonatomic , assign) bool blockRotation;
  2. 添加到AppDelegate.m功能:

    - (UIInterfaceOrientationMask)application:(UIApplication *)application  supportedInterfaceOrientationsForWindow:(UIWindow *)window 
    { 
        if (self.blockRotation) { 
         return UIInterfaceOrientationMaskPortrait; 
    } 
        return UIInterfaceOrientationMaskAll; 
    } 
    
  3. 在控制器要禁用添加此代码:

    #import "AppDelegate.h" 
    //Put to `viewDidload` 
    AppDelegate* shared=[UIApplication sharedApplication].delegate; 
    shared.blockRotation=YES; 
    

解决方案2:如果你想暂时禁用自动旋转,避免操纵方向面具做这个Hanling orientation

+0

不工作,也许是因为我使用自动布局,它不会工作? – klh63917

+0

@ klh63917检查我的编辑答案。 –

0

:你可以按照这个答案。相反,重写初始视图控制器上的shouldAutorotate方法。在执行任何自动旋转之前调用此方法。如果它返回NO,那么旋转被抑制。

所以你需要继承'UINavigationController',实现shouldAutorotate并在故事板中使用你的导航控制器类。

- (BOOL)shouldAutorotate 
{ 
    id currentViewController = self.topViewController; 

    if ([currentViewController isKindOfClass:[DetailViewController class]]) 
     return NO; 

    return YES; 
}