如何设置仅为竖屏方向?

11

我想将UIViewController设置为纵向模式,我尝试添加

- (UIInterfaceOrientation) preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationPortrait;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}

- (BOOL)shouldAutorotate {
    return [UIApplication sharedApplication].statusBarOrientation != UIDeviceOrientationPortrait;
} 

但是当我将手机横向拿起,然后进入这个UIViewController时,

我会先进入横屏,然后旋转到竖屏!

但我不想显示横屏,我想立即显示竖屏,

是否有错误的设置?

编辑

我将错误的ViewController称为"vcA",它从"vcB"呈现出来

在vcB的viewDidAppear中,我调用了

[self presentViewController:vc animated:NO completion:nil];

然后如果vcB处于横屏状态,则vcA将以横屏显示,

如果稍微延迟一下,比如:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    [self presentViewController:vc animated:NO completion:nil];
});

它将显示为纵向,但我不知道为什么会这样!

回答

最终,我找到了根本原因!

  1. 当我启动应用程序时,它停留在纵向模式下,

  2. 启动后,vcB是我调用的第一个VC,

  3. 手机保持横向状态,所以当viewDidAppear在vcB中调用时,它会调用旋转到横向

  4. 同时在viewDidAppear中,我还调用了present:vcA

  5. 因此,当前视图必须同时执行旋转到横向和呈现vcA(应该是纵向!!)

  6. 然后发生了糟糕的情况!

解决方案

只需在“vcB”中禁用第一次启动时的旋转,然后在viewDidAppear中,它将仅调用present:vcA

非常感谢大家!


你尝试过使用viewWillAppear来强制视图为竖屏吗? - jacob bullock
是的,我已经尝试过了。它可以正确地旋转到纵向模式,但它也会首先显示为横向模式,我该如何禁用横向视图?我不想显示横向模式,因为它不受支持! - Devin
@Devin 请查看这个答案,或许可以帮到你 https://dev59.com/05jga4cB1Zd3GeqPPtKY#38308987 - Reinier Melian
最终,我找到了答案,非常感谢。 - Devin
3个回答

13
  1. 打开Xcode项目的“通用设置”

  2. 找到“部署信息”

  3. 检查设备方向是否仅为“纵向”。

    输入图像描述

或者

- (void)viewWillAppear:(BOOL)animated {

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

- (BOOL)shouldAutorotate{
    return NO;
 }

我只想在当前的视图控制器中设置纵向模式,更改“常规”选项不适用于我。我尝试在viewWillAppear中添加功能,但它仍然首先显示横向模式! - Devin
是的,我也尝试过这个!它会在横向模式下停止。我发现了一些可能导致这种情况发生的东西,很快就会添加上去! - Devin

6
  1. 选择你的项目->目标->项目->常规
  2. 根据屏幕截图勾选或取消勾选(在部署下面)
  3. 确保你勾选了“需要全屏”,否则无法提交你的应用到应用商店。

enter image description here


4
Xcode版本13.2.1 中,如果使用带有 SceneDelegate 的项目,则情况与Web通常不同。
class AppDelegate{
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return UIInterfaceOrientationMask.portrait
    }
}

它能正常工作


以下不太好使

44


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