Detect Device Orientation in SwiftUI

DevTechie Inc
Jun 24, 2022


Photo by Mediamodifier on Unsplash

Today we will look at a SwiftUI recipe to detect device’s orientation.

Final product will look like this:

We will start with a custom modifier called DetectOrientation, which will take orientation as binding property and add an observer on NotificationCenter to subscribe orientation change notifications.

struct DetectOrientation: ViewModifier {
    
    @Binding var orientation: UIDeviceOrientation
    
    func body(content: Content) -> some View {
        content
            .onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)) { _ in
                orientation = UIDevice.current.orientation
            }
    }
}
Next, we will create an extension in View for easy access to our modifier.

extension View {
    func detectOrientation(_ orientation: Binding<UIDeviceOrientation>) -> some View {
        modifier(DetectOrientation(orientation: orientation))
    }
}
With modifier in place, we are ready to use it inside our View. This view will be called OrientationExample and will have a State property for orientation which will be passed into the modifier.

struct OrientationExample: View {
    
    @State private var orientation = UIDevice.current.orientation
    
    var body: some View {
        VStack {
            if orientation.isLandscape {
                HStack {
                    Image(systemName: "heart.fill")
                    Text("DevTechie")
                    Image(systemName: "heart.fill")
                }
                .font(.largeTitle)
                .foregroundColor(.orange)
            } else {
                VStack {
                    Image(systemName: "heart.fill")
                    Text("DevTechie")
                    Image(systemName: "heart.fill")
                }
                .font(.largeTitle)
                .foregroundColor(.orange)
            }
        }.detectOrientation($orientation)
    }
}
Final output:



With that we have reached the end of this article. Thank you once again for reading. Subscribe to our weekly newsletter at https://www.devtechie.com