如何在纵向模式下锁定viewController

时间:2015-12-28 08:02:45

标签: ios swift swift2 uitabbarcontroller ios9.1

我在swift中使用iOS应用程序。我使用UITabBarController作为rootViewController。我在一个viewController中有视频列表。此viewController仅支持纵向模式,用户选择视频,然后使用showViewController方法输入playerController,可以同时支持方向(纵向和横向模式)。如果视频完成则播放器控制器弹出到视频列表控制器。一切都很好,但用户可以在视频结束时旋转屏幕(如剩余时间1或0​​秒),然后视频列表viewController进入横向模式。 我已尝试使用此代码在纵向模式下设置播放器方向。

let value = UIInterfaceOrientation.Portrait.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")

但没有奏效。如何解决这个问题。

2 个答案:

答案 0 :(得分:6)

要在模式中锁定viewController,请执行以下操作:

在AppDeletegate中添加:

var shouldSupportAllOrientation = false
func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {
    if (shouldSupportAllOrientation == true){
        return UIInterfaceOrientationMask.All
    }
    return UIInterfaceOrientationMask.Portrait
}

现在转到每个视图,并在viewWillAppear中添加以下内容:

仅限肖像模式

let appdelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appdelegate.shouldSupportAllOrientation = false

所有模式

let appdelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appdelegate.shouldSupportAllOrientation = true

<强>更新
如果您想在更改视图/选项卡时再从风景回到纵向,请添加以下代码

let value = UIInterfaceOrientation.Portrait.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")

Swift 3.x版本

在AppDelegate类中添加

var shouldSupportAllOrientation = false
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    if (shouldSupportAllOrientation == true){
        return UIInterfaceOrientationMask.all
    }
    return UIInterfaceOrientationMask.portrait
}

在viewController中添加

// Portrait mode
let appdelegate = UIApplication.shared.delegate as! AppDelegate
appdelegate.shouldSupportAllOrientation = false

// All modes
let appdelegate = UIApplication.shared.delegate as! AppDelegate
appdelegate.shouldSupportAllOrientation = true

Swift 4版本:

在AppDelegate中,添加以下内容:

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

在每个viewController中添加以下内容:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    let appdelegate = UIApplication.shared.delegate as! AppDelegate
    appdelegate.shouldSupportOrientation = .portrait // set desired orientation

    let value = UIInterfaceOrientation.portrait.rawValue // set desired orientation
    UIDevice.current.setValue(value, forKey: "orientation")
}

这将锁定您的视图并旋转它。

答案 1 :(得分:2)

首先,您必须转到常规项目设置并确保您的设备方向&#34;设置为纵向(可选择颠倒)

enter image description here

然后在info.pList文件中,

检查键支持的界面方向。删除除唯一肖像键以外的所有键。查看下面的图片。

enter image description here

这会强制您的应用以纵向身份运行。即使您在横向模式下关闭播放器,您的应用也会回到纵向模式。

相关问题