Created
November 16, 2021 10:33
-
-
Save Martini024/421d9f715dab4355b7f5b0b845fb9c20 to your computer and use it in GitHub Desktop.
SwiftUI game orientation and home indicator setup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import UIKit | |
@main | |
struct MyApp: App { | |
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate | |
var body: some Scene { | |
WindowGroup { | |
ContentView() | |
.onDisappear { | |
// Use if want special orientation use only on this view | |
DispatchQueue.main.async { | |
UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation") | |
UINavigationController.attemptRotationToDeviceOrientation() | |
} | |
} | |
.onAppear { | |
UIDevice.current.setValue(UIInterfaceOrientation.landscapeRight.rawValue, forKey: "orientation") | |
UINavigationController.attemptRotationToDeviceOrientation() | |
} | |
} | |
} | |
} | |
class AppDelegate: NSObject, UIApplicationDelegate { | |
static var orientationLock = UIInterfaceOrientationMask.landscape | |
// Lock orientation to landscape only | |
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask { | |
return AppDelegate.orientationLock | |
} | |
// Apply custom scene delegate | |
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { | |
let config = UISceneConfiguration(name: "Scene Delegate", sessionRole: connectingSceneSession.role) | |
config.delegateClass = SceneDelegate.self | |
return config | |
} | |
} | |
// Custom SceneDelegate wrap ContentView inside custome HostingController | |
class SceneDelegate: UIResponder, UIWindowSceneDelegate { | |
var window: UIWindow? | |
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { | |
if let windowScene = scene as? UIWindowScene { | |
let window = UIWindow(windowScene: windowScene) | |
let rootView = ContentView() | |
let hostingController = HostingController(rootView: rootView) | |
window.rootViewController = hostingController | |
self.window = window | |
window.makeKeyAndVisible() | |
} | |
} | |
} | |
// Custom HostingController with home indicator settings to lock indicator after a short while, and require double swipe to exit the app | |
class HostingController: UIHostingController<ContentView> { | |
override var prefersHomeIndicatorAutoHidden: Bool { | |
return false | |
} | |
override var preferredScreenEdgesDeferringSystemGestures: UIRectEdge { | |
return .bottom | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment