-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSTOrientationManager.swift
More file actions
58 lines (46 loc) · 2.38 KB
/
Copy pathSTOrientationManager.swift
File metadata and controls
58 lines (46 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//
// STOrientationManager.swift
// STBaseProject
//
// Created by 寒江孤影 on 2026/06/30.
//
import UIKit
public final class STOrientationManager {
public static let shared = STOrientationManager()
public var defaultInterfaceOrientations: UIInterfaceOrientationMask = .portrait
public var supportedInterfaceOrientations: UIInterfaceOrientationMask {
self.overrideInterfaceOrientations ?? self.defaultInterfaceOrientations
}
private var overrideInterfaceOrientations: UIInterfaceOrientationMask?
private init() {}
public func requestInterfaceOrientations(_ orientations: UIInterfaceOrientationMask, in windowScene: UIWindowScene? = nil) {
self.overrideInterfaceOrientations = orientations
self.requestGeometryUpdate(orientations, in: windowScene)
}
public func restoreDefaultInterfaceOrientations(in windowScene: UIWindowScene? = nil) {
self.overrideInterfaceOrientations = nil
self.requestGeometryUpdate(self.defaultInterfaceOrientations, in: windowScene)
}
private func requestGeometryUpdate(_ orientations: UIInterfaceOrientationMask, in windowScene: UIWindowScene?) {
let targetWindowScene = windowScene ?? self.activeWindowScene()
if #available(iOS 16.0, *), let targetWindowScene {
targetWindowScene.requestGeometryUpdate(.iOS(interfaceOrientations: orientations)) { error in
print("[STOrientationManager] requestGeometryUpdate failed: \(error.localizedDescription)")
}
} else {
UIDevice.current.setValue(self.preferredOrientation(for: orientations).rawValue, forKey: "orientation")
}
UIViewController.attemptRotationToDeviceOrientation()
}
private func preferredOrientation(for orientations: UIInterfaceOrientationMask) -> UIInterfaceOrientation {
if orientations.contains(.portrait) { return .portrait }
if orientations.contains(.landscapeLeft) { return .landscapeLeft }
if orientations.contains(.landscapeRight) { return .landscapeRight }
if orientations.contains(.portraitUpsideDown) { return .portraitUpsideDown }
return .portrait
}
private func activeWindowScene() -> UIWindowScene? {
let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }
return scenes.first { $0.activationState == .foregroundActive } ?? scenes.first
}
}