锁定iOS Swift应用程序的屏幕方向为纵向

18

我正在创建一个仅支持竖屏模式的应用程序。我不想要横屏或倒置的竖屏。我尝试了一些代码,可以让我锁定为竖屏模式。

我正在使用navigationcontroller和presentviewcontroller。现在我的问题是: 1. 如果我把设备倒置并打开我的应用程序,它会以倒置模式打开,这是错误的。 2. 我点击某个按钮进入presentviewcontroller后,它会返回到竖屏模式。

我希望所有的navigationcontroller和presentviewcontroller都在竖屏模式下

我的代码:

我在目标 -> 通用 -> 部署信息 -> 竖屏中将设备方向设置为竖屏。

在我的appdelagate.swift中:

func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {
        return UIInterfaceOrientationMask.Portrait
    }

在我的第一个视图控制器中,基本上是导航控制器的子视图。

override func shouldAutorotate() -> Bool {


            return false
        }

        override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
            return [UIInterfaceOrientationMask.Portrait ]
        }

编辑 1:

我还设置了StoryBoard -> ViewController -> Attribute Inspector -> Orientation -> Portrait

编辑 2:

我的设置文件enter image description here


请检查这个链接,它对我有效:https://dev59.com/nV4b5IYBdhLWcg3wlihP - Pradeep Kashyap
3个回答

40

前往目标 --> 常规,将方向模式设置为竖屏。

enter image description here

同时检查Info.plist文件。确保Supported Interface Orientations只包含一个值(Portrait)。有时候从设置中删除了某些选项,但未在plist文件中更新。

enter image description here


请按照答案中的建议检查 Info.plist 文件。这可能是您的情况。 - technerd
谢谢。我错过了一行代码,整个应用程序就出问题了。我是iOS的新手,谢谢。 - Amsheer
在我的情况下,iPad 有一个额外的选项,允许所有方向类型。因此,我只留下了“纵向(底部主页按钮)”,现在一切都完美地运作。 - Ivanka Todorova

3
如果您的应用程序不支持分屏视图,则应选择“要求全屏”选项。这解决了我的纵向模式问题。 enter image description here 如果此方法无法解决问题,请在info.plist中添加Array类型的Supported interface orientations键。并将字符串项添加到该数组中,值为Portrait (bottom home button)

enter image description here


谢谢。我错过了一行代码,整个应用程序就出问题了。我是iOS的新手,感谢Technerd在你之前提供了解决方案。所以我接受了他的答案。我给你点赞了。 - Amsheer

0

对我来说,唯一有效的解决方案是添加:

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    .portrait
}

在应用程序的委托类中,如问题本身所示。

我正在使用没有任何故事板文件的SwiftUI,甚至连启动画面也是如此。


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