【问题标题】:ObjC disable ViewController rotationObjC 禁用 ViewController 旋转
【发布时间】:2016-01-10 18:49:37
【问题描述】:

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

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

【问题讨论】:

  • 请访问我的回答here
  • 你可能会遗漏一些东西,我已经测试了这段代码,它对我来说工作正常。

标签: objective-c


【解决方案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

【讨论】:

  • 不起作用,可能是因为我使用了自动布局,它不起作用?
【解决方案2】:

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

因此,您需要继承“UINavigationController”,实现 shouldAutorotate 并在情节提要中使用导航控制器类。

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

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

    return YES;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-13
    • 1970-01-01
    • 2014-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多