Handling Device Orientation Change using SwiftUI

More often than not, app developers need to present views differently depending on the orientation of the device.

Lets quickly see how to get this done.

First step is to be able to get a notification whenever orientation changes. This is pretty straight forward

// Somewhere in your model init code
NotificationCenter.default.addObserver(self, selector: #selector(yourModel.rotated), name: UIDevice.orientationDidChangeNotification, object: nil)

rotated() is the @objc function defined inside yourModel that is invoked on orientation change.

@objc func rotated() {
        self.isPotrait =  UIDevice.current.orientation.isPortrait
    }

Next step is to build your view based on this notification

Assumption here is that:

  • your Model is already an ObservableObject
class MyModel : ObservableObject  {
    var isPotrait :Bool
    // code
}
  • And being passed to your UI as an environment object
struct MyView : View {
    @EnvironmentObject var model : MyModel
    // … rest of the code
 }

all you need to do to change your View based on orientation is :

  • @Publish your isPortrait variable in your model
class MyModel : ObservableObject  {
    @Published var isPotrait :Bool 
    // code
}
  • And have UI use this variable to present accordingly
struct MyView : View {
    @EnvironmentObject var model : MyModel
    // … rest of the code
    if model.isPotrait  {
	… // .Code for portrait mode
    } else  {
	… // .Code for portrait mode
    }
}

That is all it takes to support device orientation change in your iOS app. Happy Coding..

No related posts.

Leave a Reply

Required fields are marked *.


This site uses Akismet to reduce spam. Learn how your comment data is processed.