如何在 SwiftUI 中禁用设备旋转动画?

ade*_*ris 11 animation screen-rotation ios swiftui

对于 UIKit 禁用设备旋转动画,您可以重写 viewWillTransitionToSize 方法。 禁用方向改变旋转动画 但是在 SwiftUI 中实现这一点的最佳方法是什么?

Asp*_*eri 1

我们几乎可以用同样的方式做到这一点 - 创建一个带有动画拦截器的辅助视图控制器,并在背景中使用它作为可表示的。

使用 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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

和用法:

    WindowGroup {
        ContentView()
          .background(HelperView())   // << here !!
    }
Run Code Online (Sandbox Code Playgroud)

GitHub 上的模块