强制iOS 7横屏显示

10
我尝试了以下方法来强制在一个视图中横向显示:

我尝试了以下方法来强制在一个视图中横向显示:

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscape;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationLandscapeLeft;
}

- (BOOL)shouldAutorotate{
    return YES;
}

都没起作用。请注意,我在模拟器和iPad上测试。

谢谢

3个回答

22

以下是我如何使用NavigationViewController强制将我的一个视图设置为横屏的方法:

  1. 实现了这个答案:https://dev59.com/A2cs5IYBdhLWcg3wrl4Z#12662433

  2. 在View Controller中导入了message:objc/message.h

  3. 在viewDidLoad方法中添加了以下代码:

objc_msgSend([UIDevice currentDevice], @selector(setOrientation:), UIInterfaceOrientationLandscapeLeft);

希望能够帮助某些人。


这个逻辑会被苹果批准吗? - Mc-
看起来我只需要步骤2和3(步骤1似乎是可选的)。 - Jeef
用第一步,您可以防止用户再次进入纵向模式。 - diogo.appDev
我已经在两个应用程序中运行它。 - diogo.appDev
这在iOS模拟器上似乎可以工作,但在实际设备上却不行? - just.jimmy
这绝对是错误的。如果您试图强制特定界面方向,您需要调用 [UIApplication sharedApplication].statusBarOrientation = UIInterfaceOrientationPortrait;。 苹果提供了两个非常相似但非常不同的枚举:UIDeviceOrientation 和 UIInterfaceOrientation。设备属性是只读的,因为您无法强制物理设备更改方向!statusBarOrientation 是可写的,并且将执行您想要使用 setValue:forKey: 进行的操作。 - Dan Jackson

7
被接受的答案似乎在iOS 7.1.2上无效。(它在模拟器上可以工作,但在设备上运行时却无法工作。)然而,以下方法似乎有效:
[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIInterfaceOrientationPortrait] forKey:@"orientation"];

[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIInterfaceOrientationLandscapeLeft] forKey:@"orientation"];

我的解决方案在搭载iOS 7.1.2的iPhone 4上运行良好。你用的是什么设备? - diogo.appDev

1
int shouldShowInLandscape = 0;

-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {


    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(forceToLandscape:)
                                                 name:@"yourNameNotification"
                                               object:nil];

}

-(NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{

    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
    {
              return UIInterfaceOrientationMaskLandscapeLeft;
    } else {
            if(shouldShowInLandscape)
            {
                return UIInterfaceOrientationMaskLandscape;
            }
            return UIInterfaceOrientationMaskPortrait;
    }
}

-(void) forceToLandscape:(NSNotification*) theNot
{
    shouldShowInLandscape = [[theNot object] intValue];

}

// 来自UIViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter]
     postNotificationName:@"yourNameNotification"
     object:[NSString stringWithFormat:@"1"]];
}

-(void) viewDidDisappear:(BOOL)animated
{

        [[NSNotificationCenter defaultCenter]
     postNotificationName:@"yourNameNotification"
     object:[NSString stringWithFormat:@"0"]]; 

}

//移除通知中心


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接