Reading time: 1 min

This recipe shows how to detect device orientation in SwiftUI. You can also use a binding to detect orientation changes.

The end result looks like this:

preview

The recipe relies on listening to UIDevice.orientationDidChangeNotification notifications, which are automatically posted whenever device orientation changes. Here's the code:

struct OrientationDetector: ViewModifier {
  @Binding var orientation: UIDeviceOrientation

  func body(content: Content) -> some View {
    content
      .onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)) { _ in
        orientation = UIDevice.current.orientation
      }
  }
}

extension View {
  func detectOrientation(_ binding: Binding<UIDeviceOrientation>) -> some View {
    self.modifier(OrientationDetector(orientation: binding))
  }
}

Then, building an orientation-aware view is as easy as this:

struct OrientationTest: View {
  @State private var orientation = UIDevice.current.orientation

  var body: some View {
    Group {
      if orientation.isLandscape {
        Text("I'm in landscape!")
      } else {
        Text("I'm in portrait!")
      }
    }
    .detectOrientation($orientation)
  }
}

Next Post Previous Post