Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
SwiftUI DeviceOrientationObserver
import SwiftUI
public final class DeviceOrientationObserver: ObservableObject {
public init(notificationCenter: NotificationCenter = .default) {
observation = notificationCenter.addObserver(
forName: UIDevice.orientationDidChangeNotification,
object: nil,
queue: .main,
using: { [weak self] notification in
self?.value = (notification.object as? UIDevice)?.orientation ?? .unknown
}
)
}
@Published public var value: UIDeviceOrientation = .unknown
private var observation: NSObjectProtocol?
}
public extension UIDeviceOrientation {
var angle: Angle {
switch self {
case .unknown: return .zero
case .portrait: return .zero
case .portraitUpsideDown: return .degrees(180)
case .landscapeLeft: return .degrees(90)
case .landscapeRight: return .degrees(-90)
case .faceUp: return .zero
case .faceDown: return .zero
@unknown default: return .zero
}
}
}
// MARK: - Example usage
struct ContentView: View {
@ObservedObject var deviceOrientation = DeviceOrientationObserver()
var body: some View {
Image(systemName: "arrow.up") //
.imageScale(.large)
.rotationEffect(deviceOrientation.value.angle) // will point up, regardless device orientation
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment