How to detect device orientation in swiftUI ?

To check current device orientation in iOS application
1. NotificationCenter.default.publisher for detecting device orientation
2. .onReceive(… receive live values from the element on
3. getColor will return the color based on device orientation

struct ContentView: View {
    
    @State var currentOrientation = UIDevice.current.orientation
    
    let orientationHasChanged = NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)
        .makeConnectable()
        .autoconnect()
    
    var body: some View {
        Group {
            Text("Hello")
                .background(getColor())
            
        }.onReceive(orientationHasChanged) { _ in
            self.currentOrientation = UIDevice.current.orientation
        }
    }
    
    func getColor() -> Color {
        if self.currentOrientation == .portrait || self.currentOrientation == .portraitUpsideDown {
            return .red
        } else {
            return .yellow
        }
    }
    
}

Leave a Comment

Your email address will not be published. Required fields are marked *