【问题标题】:Portrait orientation [closed]纵向[关闭]
【发布时间】:2014-03-13 07:57:36
【问题描述】:

我有一个显示为全屏的视图。我希望显示的全屏视图仅限于纵向。

谁能帮我限制只有一个视图作为肖像?它不应该变成横向。

【问题讨论】:

标签: ios objective-c ipad


【解决方案1】:

您使用的代码取决于您所针对的 iOS:

iOS 6+

有一个名为 supportedInterfaceOrientations 的方法可以满足您的需求:

- (NSUInteger)supportedInterfaceOrientations
{
    //If you want to support landscape
    return UIInterfaceOrientationMaskAll;
    
    //If you don't
    return UIInterfaceOrientationMaskPortrait;
}

 - (BOOL)shouldAutorotate {
    return YES;
}

在每个视图控制器中放入相应的返回语句。


iOS 5 及更早版本:

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

【讨论】:

  • 是的。谢谢它在我的模拟器上工作。我将在 iPad 上构建它并检查并给你反馈。
  • 嘿,它在我的主应用程序中不起作用,其中显示了许多视图控制器。在我想限制为肖像的那个中,我添加了上面的代码,但它不起作用。它也显示在景观中。你还有其他方法吗?
  • 你为哪个 iOS 版本写这篇文章?
  • 检查我的编辑。我忘了包含 autorotate 方法,我添加了 iOS 5 的代码-
  • 我在 iOS 6 及更高版本上使用它。
【解决方案2】:

如果您使用的是 VC 之间呈现的模型,@David 的答案是正确的。 但是如果你使用UINavigationControllerpush/pop,事情会更复杂。

- (NSUInteger)supportedInterfaceOrientations- (BOOL)shouldAutorotate 仅在设备旋转或根控制器更改后调用。 push/pop 不会成功。


在 iOS5 及之前的版本中,有一个 API:

[[UIDevice currentDevice] setOrientation: UIInterfaceOrientationPortrait];

但它已被弃用。 Apple 将其设为私有。

在iOS 6+中仍然可以使用objc runtime api调用,如:

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

[[UIDevice currentDevice] setValue:@(UIInterfaceOrientationPortrait)
                            forKey:@"orientation"];

注意:它是私有 API,这可能会被 App Store 拒绝。


另一种棘手的方法是,只需呈现一个空 VC,然后在 viewDidAppear 中将其关闭,类似于:

[self presentViewController:[UIViewController new]
              animated:NO
              completion:^{
                  [self dismissViewControllerAnimated:NO completion:nil];
              }];

这将使- (NSUInteger)supportedInterfaceOrientations- (BOOL)shouldAutorotate 被调用。


如果您对以上内容不满意。尝试制作自己的 NavigationController,或者 看看这个问题:Why can't I force landscape orientation when use UINavigationController?

【讨论】:

  • 谢谢它运作良好。但是有一个问题,当该视图打开时它变成纵向,但是当我将它向左旋转 4 次时,它第四次变成横向。 :(
  • @user3202087 根据您的描述,我现在无法弄清楚为什么,也许您可​​以提出一个新问题并发布代码。
  • 实际上,我使用的是navigationController push/pop,这就是为什么David 的代码无法正常工作并且您的代码有问题(上面提到的那个),但我将push/pop 更改为呈现viewController。无论如何,感谢您提供的帮助。 :)
  • 这绝对是错误的。如果你试图强制一个特定的界面方向,你想调用[UIApplication sharedApplication].statusBarOrientation = UIInterfaceOrientationPortrait; Apple 提供了两个相似但非常不同的不同枚举:UIDeviceOrientation 和 UIInterfaceOrientation。设备属性是只读的,因为你不能强制物理设备改变方向! statusBarOrientation 可写的,并且会做你试图用 setValue:forKey: 做的事情
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-12
  • 1970-01-01
  • 2016-08-29
  • 2013-12-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多