如何改變單一頁面的螢幕旋轉方向

Zhi-Hong Lin
Jul 13, 2018

--

首先在 AppDelegate.swift 裡加入一個變數 orientationLock

// 宣告螢幕能夠的旋轉方向
var orientationLock = UIInterfaceOrientationMask.portrait

然後在 supportedInterfaceOrientationsForWindow 這個 function 回傳建立定義的變數 orientationLock

//螢幕旋轉後最終會調用的function
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return orientationLock}

接下來宣告一個 class ,建立兩個 static function,就可以透過這個 class 來自定義頁面的旋轉方向

使用方式

viewWillAppear 裡設定要旋轉的方向後

override func viewWillAppear(_ animated: Bool) {super.viewWillAppear(animated)UIUtils.lockOrientation(.landscape, andRotateTo: .landscapeRight)}

記得在 viewWillDisappear 設定回原來的旋轉方向

override func viewWillDisappear(_ animated: Bool) {super.viewWillDisappear(animated)UIUtils.lockOrientation(.portrait, andRotateTo: .portrait)}

螢幕旋轉相關知識

UIDeviceOrientation (裝置方向)

public enum UIDeviceOrientation : Int {
case unknown
case portrait // 裝置 vertically 方向, home 键在下方
case portraitUpsideDown // 裝置 vertically 方向, home 键在上方
case landscapeLeft // 裝置 horizontally 方向, home 键在右方
case landscapeRight // 裝置 horizontally 方向, home 键在左方
case faceUp // 裝置 flat 方向, 螢幕朝上
case faceDown // 裝置 flat 方向, 螢幕朝下
}

UIInterfaceOrientation(界面方向)

public enum UIInterfaceOrientation : Int {
case unknown
case portrait
case portraitUpsideDown
case landscapeLeft
case landscapeRight
}

UIInterfaceOrientationMask(用來控制允許轉向的方向,對應UIInterfaceOrientation )

public struct UIInterfaceOrientationMask : OptionSet {
public init(rawValue: UInt)
public static var portrait: UIInterfaceOrientationMask { get }
public static var landscapeLeft: UIInterfaceOrientationMask { get }
public static var landscapeRight: UIInterfaceOrientationMask { get }
public static var portraitUpsideDown: UIInterfaceOrientationMask { get }
public static var landscape: UIInterfaceOrientationMask { get }
public static var all: UIInterfaceOrientationMask { get }
public static var allButUpsideDown: UIInterfaceOrientationMask { get }
}

--

--