首页 > 解决方案 > 关闭 MainScreen 视图控制器

问题描述

我注意到,当我从主控制器视图(mainScreen)
切换到另一个视图(例如:secondScreen)时,我没有关闭我的 mainScreen
并打开 secondScreen,我只是在我的 mainScreen
顶部打开我的 secondScreen。有没有办法让我关闭我的主屏幕?
我用来从 mainScreen 切换到 secondScreen 的代码:

let storyboard = UIStoryboard(name: "MainScreen", bundle: nil) 
let secondVC = storyboard.instantiateViewController(identifier: "SecondScreen" 
self.dismiss(animated: true, completion: nil) 
self.loadView() show(secondVC, sender: self) 

我用来返回 mainScreen 的代码:

dismiss(animated: true, completion: nil)

// 我使用 self.dismiss() 和 self.loadView() 作为重新加载 MainScreen 的解决方案。
// 我从 SecondScreen 获取数据,该数据会更改 MainScreen 上的数据,
// 我无法以其他方式成功。

如果我们不能重新加载我们的 MainScreen,至少创建一个函数可以在
每次加载我的 MainScreen 视图时更改我的数据,那就太好了!

感谢您的时间!

标签: swiftxcode

解决方案


斯威夫特 5 - iOS 14

以下代码完全更改了您的应用程序根目录。

func coordinateToSecondVC()
{
    guard let window = UIApplication.shared.keyWindow else { return }
    let storyboard = UIStoryboard(name: "MainScreen", bundle: nil) 
    let secondVC = storyboard.instantiateViewController(identifier: "SecondScreen")
    window.rootViewController = secondVC
    window.makeKeyAndVisible()
}

如果你想推送你secondVC的导航堆栈,你可以使用这个:

func coordinateToSecondVC()
{
    guard let window = UIApplication.shared.keyWindow else { return }
    let storyboard = UIStoryboard(name: "MainScreen", bundle: nil) 
    let secondVC = storyboard.instantiateViewController(identifier: "SecondScreen")
    let navController = UINavigationController(rootViewController: secondVC)
    navController.modalPresentationStyle = .fullScreen
    window.rootViewController = navController
    window.makeKeyAndVisible()
}

然后在您想要协调时轻松调用该函数secondVC

coordinateToSecondVC()

推荐阅读