Last active
July 20, 2021 10:11
-
-
Save darrarski/84949e418a6b03dee983cfcd573d21cd to your computer and use it in GitHub Desktop.
SwiftUI DeviceOrientationObserver
This file contains 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 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