簡體   English   中英

iOS允許不同的屏幕方向而無需自動旋轉

[英]iOS Allow different screen orientation withouth autorotation

即使用戶旋轉手機,我也要保持縱向。 同時,我想用一個按鈕改變方向。 如果我僅將肖像作為支持的方向放在plist中,然后旋轉,應用程序將給我錯誤。 如果我將所有受支持的方向都放置了但應該將shouldAutorotate方法設置為NO,則應用程序崩潰。 因此,基本上,如我所見,如果讓應用程序自動旋轉,則只能支持多種方向。

我能達到我所需要的嗎?

shouldAutorotate

這是一個只讀屬性。

您可以做的是:

override var shouldAutorotate: Bool {
    return false
}

也許這對您也很有趣: 如何禁用並啟用swift的自動旋轉功能?

以下代碼行可能對您有用。 以編程方式設置方向。

  1. 在您的Appdelegate類中,編寫以下代碼:

    var orientationLock = UIInterfaceOrientationMask.all

    func應用程序(_應用程序:UIApplication,supportedInterfaceOrientationsFor窗口:UIWindow?)-> UIInterfaceOrientationMask {return self.orientationLock}

2.制作自定義幫助程序類,如下所示:

struct AppUtility {

    static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {

        if let delegate = UIApplication.shared.delegate as? AppDelegate {
            delegate.orientationLock = orientation
        }
    }

    /// OPTIONAL Added method to adjust lock and rotate to the desired orientation
    static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) {

        self.lockOrientation(orientation)

        UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
    }

}
  1. 然后在您的期望ViewController中使用它,例如:

    覆蓋func viewDidAppear(_動畫:布爾){super.viewDidAppear(動畫)

     AppUtility.lockOrientation(.portrait) // Or to rotate and lock // AppUtility.lockOrientation(.portrait, andRotateTo: .portrait) 

    }

    覆蓋func viewWillDisappear(_動畫:布爾){super.viewWillDisappear(動畫)

     // Don't forget to reset when view is being removed AppUtility.lockOrientation(.all) 

    }

注意:請記住,已從目標設置中選中了需要全屏顯示選項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM