©️ OverlookArt
首页 / AppleDevelop / UIKit / 设备方向

设备方向

APP 支持的屏幕方向

虽然在 Xcode 中设置了 iOS 项目所支持的方向,但是可以在 AppDelegate 中动态修改 APP 支持的方向

 1// AppDelegate.swift 
 2
 3/// 是否允许支持所有方向
 4public var allowRotation: Bool = false
 5
 6func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
 7    if allowRotation { return .all }    
 8    return .portrait
 9}
10
11// ViewController.swift
12override func viewWillAppear(_ animated: Bool) {
13    super.viewWillAppear(animated)
14    if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
15        appDelegate.allowRotation = true
16    }  
17}
18
19override func viewDidDisappear(_ animated: Bool) {
20    super.viewDidDisappear(animated)
21    if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
22        appDelegate.allowRotation = false
23    }
24}

手动旋转屏幕方向

 1// viewContoller.swift
 2
 3// 竖屏模式
 4private func halfScreen() {
 5    if #available(iOS 16.0, *) {
 6        guard let windowScene = self.view.window?.windowScene else { return }
 7        UIViewController.attemptRotationToDeviceOrientation()
 8        let iOSWindowScene = UIWindowScene.GeometryPreferences.iOS()
 9        iOSWindowScene.interfaceOrientations = .portrait
10        windowScene.requestGeometryUpdate(iOSWindowScene) { error in
11                
12        }
13    } else {
14        UIDevice.current.setValue(UIDeviceOrientation.portrait.rawValue, forKey: "orientation")
15    }
16}
17
18// 横屏模式
19private func fullScreen() {
20    if #available(iOS 16.0, *) {
21        guard let windowScene = self.view.window?.windowScene else { return }
22        UIViewController.attemptRotationToDeviceOrientation()
23        let iOSWindowScene = UIWindowScene.GeometryPreferences.iOS()
24        iOSWindowScene.interfaceOrientations = .landscapeLeft
25        windowScene.requestGeometryUpdate(iOSWindowScene) { error in
26                
27        }
28    } else {
29        UIDevice.current.setValue(UIDeviceOrientation.landscapeLeft.rawValue, forKey: "orientation")
30    }
31}