Skip to content

Instantly share code, notes, and snippets.

@Martini024
Created November 16, 2021 10:33
Show Gist options
  • Save Martini024/421d9f715dab4355b7f5b0b845fb9c20 to your computer and use it in GitHub Desktop.
Save Martini024/421d9f715dab4355b7f5b0b845fb9c20 to your computer and use it in GitHub Desktop.
SwiftUI game orientation and home indicator setup
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