簡體   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