Created
May 15, 2024 23:13
-
-
Save mobibob/44c4eb26b6adc64b10ab3f0d9d72b308 to your computer and use it in GitHub Desktop.
SwiftUI - Detect orientation changes
This file contains hidden or 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 Foundation | |
import SwiftUI | |
class OrientationObserver: NSObject { | |
let action: (UIDeviceOrientation) -> Void | |
init(action: @escaping (UIDeviceOrientation) -> Void) { | |
self.action = action | |
super.init() | |
registerForOrientationChanges() | |
} | |
private func registerForOrientationChanges() { | |
NotificationCenter.default.addObserver( | |
self, | |
selector: #selector(onOrientationChange(_:)), | |
name: UIDevice.orientationDidChangeNotification, object: nil) | |
} | |
private func unregisterForOrientationChanges() { | |
NotificationCenter.default.removeObserver(self, name: UIDevice.orientationDidChangeNotification, object: nil) | |
} | |
@objc func onOrientationChange(_ notification: Notification) { | |
guard let device = notification.object as? UIDevice else { return } | |
let orientation = device.orientation | |
action(orientation) | |
} | |
deinit { | |
unregisterForOrientationChanges() | |
} | |
} | |
struct OnRotateModifier: ViewModifier { | |
let observer: OrientationObserver | |
init(action: @escaping (UIDeviceOrientation) -> Void) { | |
self.observer = OrientationObserver(action: action) | |
} | |
func body(content: Content) -> some View { | |
content | |
.onAppear() {} | |
.onDisappear() {} | |
} | |
} | |
//// Usage (snippet) | |
@State var isPortrait = false | |
VStack() { | |
if (isPortrait) { | |
Text("Top") | |
Spacer() | |
CameraView() | |
Spacer() | |
Text("Bottom") | |
} else { | |
HStack { | |
Text("Top") | |
Spacer() | |
CameraView() | |
Spacer() | |
Text("Bottom") | |
} | |
} | |
} | |
.modifier(OnRotateModifier { orientation in | |
isPortrait = orientation.isPortrait | |
}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment