iosanimationswiftuiscreen-rotation

How to disable the device rotation animation in SwiftUI?


For UIKit to disable the device rotation animation you could override the viewWillTransitionToSize method. Disable orientation change rotation animation But what would be the best way to achieve this in SwiftUI?


Solution

  • We can do this almost in the same way - create a helper view controller with animation blocker and use it inside background as representable.

    Tested with Xcode 13.4 / iOS 15.5

    struct HelperView: UIViewControllerRepresentable {
        func makeUIViewController(context: Context) -> some UIViewController {
            OrientationHandler()
        }
    
        func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
        }
    
        class OrientationHandler: UIViewController {
            override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
                coordinator.animate(alongsideTransition: nil) { _ in
                    UIView.setAnimationsEnabled(true)
                }
                UIView.setAnimationsEnabled(false)
                super.viewWillTransition(to: size, with: coordinator);
            }
        }
    }
    

    and usage:

        WindowGroup {
            ContentView()
              .background(HelperView())   // << here !!
        }
    

    Module on GitHub