在 iOS 上,是否可以在设备方向改变时自动重新启动应用程序? Android 有这个功能(只要确保 android:configChanges 不包括方向)。
最佳答案
iOS 中没有可用的方法来重新启动您的应用程序,但是您可以在方向更改时手动重新实例化初始根 UIViewController
。
要重新实例化根 UIViewController
,您可以在 AppDelegate
类中使用以下static 函数:
static func getWindow() -> UIWindow? {
return UIApplication.shared.keyWindow
}
static func resetViewController() {
let window = getWindow()
let controller = ... /// Instantiate your inital `UIViewController`
window?.rootViewController = controller
window?.makeKeyAndVisible()
}
要监听方向变化,请使用 UIViewController
中的以下方法:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
AppDelegate.resetViewController() /// "Restarts" application
}
虽然这是一种可行的方法,但我强烈建议您不要在发生方向更改时重新启动您的应用程序,而只是按照 Apple 的规定处理方向更改。
关于iOS - 在方向改变时重新启动应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59190165/