NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

How to detect device rotation

Paul Hudson    @twostraws   

Updated for Xcode 14.2

SwiftUI doesn’t have a built-in way to detect the user rotating their device between portrait and landscape orientation, but we can make one using a custom modifier by responding to the UIDevice.orientationDidChangeNotification notification.

This takes three steps:

  1. Creating a custom view modifier that watches for orientation changes and runs a callback function when it happens. It’s not required, but we’re going to make the callback accept a UIDeviceOrientation as its only parameter, just in case you need to know the current orientation.
  2. Wrapping that view modifier up in a View extension so that it’s easier to call.
  3. Using your custom modifier in a view of your choosing.

Important: At the time of writing view modifiers do not work with onReceive() unless you first add onAppear(), which is why it appears above. Yes, it’s empty, but it acts as a workaround for the problem.

Here’s a complete code sample:

// Our custom view modifier to track rotation and
// call our action
struct DeviceRotationViewModifier: ViewModifier {
    let action: (UIDeviceOrientation) -> Void

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

// A View wrapper to make the modifier easier to use
extension View {
    func onRotate(perform action: @escaping (UIDeviceOrientation) -> Void) -> some View {
        self.modifier(DeviceRotationViewModifier(action: action))
    }
}

// An example view to demonstrate the solution
struct ContentView: View {
    @State private var orientation = UIDeviceOrientation.unknown

    var body: some View {
        Group {
            if orientation.isPortrait {
                Text("Portrait")
            } else if orientation.isLandscape {
                Text("Landscape")
            } else if orientation.isFlat {
                Text("Flat")
            } else {
                Text("Unknown")
            }
        }
        .onRotate { newOrientation in
            orientation = newOrientation
        }
    }
}

An iPhone in portait orientation showing the word “Portrait” beside another iPhone in landscape orientation showing the word “Landscape”.

Tip: This may not work while your app is connected to Xcode’s debugger – try pushing your app to a real device, then running it manually rather than via Xcode.

Please remember that device orientation isn’t quite as useful as you might expect. Yes, on iPhone a landscape orientation means you have more horizontal space than vertical, but on iPad it’s possible for your app to be running in landscape while in split-screen mode – technically the whole screen still has a larger width than height, but the actual space allocated to our app is only a small slice of that width.

Hacking with Swift is sponsored by Essential Developer

SPONSORED From March 20th to 26th, you can join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer!

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.5/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.