Skip to content

Instantly share code, notes, and snippets.

@darrarski
Last active July 20, 2021 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darrarski/84949e418a6b03dee983cfcd573d21cd to your computer and use it in GitHub Desktop.
Save darrarski/84949e418a6b03dee983cfcd573d21cd to your computer and use it in GitHub Desktop.
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