Skip to content

Instantly share code, notes, and snippets.

@mobibob
Created May 15, 2024 23:13
Show Gist options
  • Save mobibob/44c4eb26b6adc64b10ab3f0d9d72b308 to your computer and use it in GitHub Desktop.
Save mobibob/44c4eb26b6adc64b10ab3f0d9d72b308 to your computer and use it in GitHub Desktop.
SwiftUI - Detect orientation changes
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