ObjC禁用ViewController旋转

时间:2016-01-10 18:49:38

标签: objective-c

我试图在一个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;
}

但它没有用。它将屏幕旋转为纵向,但它不会将其锁定,如果我转动设备,它会改变屏幕方向。

2 个答案:

答案 0 :(得分: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;
    
  4. 解决方案2:您可以按照以下答案:Hanling orientation

答案 1 :(得分:0)

如果要暂时禁用自动旋转,请避免操作方向遮罩来执行此操作。而是覆盖初始视图控制器上的shouldAutorotate方法。在执行任何自动旋转之前调用此方法。如果它返回NO,则旋转被抑制。

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

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

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

    return YES;
}