繁体   English   中英

如何在纵向模式下锁定viewController

[英]How to lock viewController in Portrait mode

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

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

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

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

在你的AppDeletegate中添加:

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

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

仅限Portait模式

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")
}

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

首先必须进入常规项目设置,并确保将“设备方向”设置为纵向(可选择颠倒)

在此输入图像描述

然后在info.pList文件中

检查密钥支持的接口方向。 删除除唯一肖像键以外的所有键。 查看下面的图像。

在此输入图像描述

这将迫使您的应用以纵向运行。 即使您在横向模式下关闭播放器,您的应用也会返回纵向模式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM