How it works
InterfaceOrientation is a structure that enumerates the discrete ways a user interface can be oriented: portrait, the two landscape directions, and upside-down portrait. SwiftUI uses it wherever a scene needs to reason about which way "up" the interface is presented, rather than the raw orientation of the physical device. Reach for it when your layout, content, or an immersive presentation should respond to or declare a specific interface orientation, working with a named constant instead of an angle or device sensor reading.
Hold an orientation as a typed value
Because InterfaceOrientation is a value type with a fixed set of cases, you can store and pass it like any other state. Here it backs a property,
@State private var orientation: InterfaceOrientation, seeded with the.portraitconstant so the view starts from a known orientation.Read the named constants
The type vends its values as static constants rather than free-form numbers, so you spell out exactly the orientation you mean. The example references
.portrait,.landscapeLeft,.landscapeRight, and.portraitUpsideDowndirectly, each one standing for a single, unambiguous way the interface can sit.Switch over the cases
Because the constants form a discrete, enumerable set, an InterfaceOrientation value drives a clean
switch. Thelabelproperty matchesorientationagainst each case to produce human-readable text, with adefaultarm covering any orientation not handled explicitly.Compare and reassign orientations
InterfaceOrientation values support equality, so you can test the current one and swap in another. The
Rotatebutton checksorientation == .portraitand assigns either.landscapeLeftor.portraitback into the state, toggling between two named orientations on each tap.
.landscapeLeft with .portraitUpsideDown and watch label report "Upside Down" to confirm each InterfaceOrientation constant maps to its own case.Example & preview
Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.
struct InterfaceOrientationDemo: View {
@State private var orientation: InterfaceOrientation = .portrait
var label: String {
switch orientation {
case .portrait: return "Portrait"
case .landscapeLeft: return "Landscape Left"
case .landscapeRight: return "Landscape Right"
case .portraitUpsideDown: return "Upside Down"
default: return "Unknown"
}
}
var body: some View {
VStack(spacing: 16) {
Image(systemName: "rotate.3d")
.font(.largeTitle)
Text(label)
.font(.headline)
Button("Rotate") {
orientation = orientation == .portrait ? .landscapeLeft : .portrait
}
.buttonStyle(.borderedProminent)
}
.padding()
}
}