【问题标题】:How to use Coordinator pattern in Xcode 11/iOS13 on UIKit?如何在 UIKit 上的 Xcode 11/iOS13 中使用协调器模式?
【发布时间】:2020-03-15 21:11:30
【问题描述】:

我一直在尝试通过使用 Storyboards 作为界面设计在 Xcode 11.2 上创建一个新应用来学习协调器模式。
我关注了 Paul Hudson 的 this video,但在需要将代码添加到 AppDelegate.swift 文件时,我在第 12 分钟卡住了。就像应用程序将启动一样,第一个视图控制器将显示但不会导航。
我应该更改什么,或者更好的是,我应该将当前代码移到哪里才能使其正常工作?
整个项目可以找到here.
简而言之,在 iOS 12 及之前的 AppDelegate 中的代码是这样的:

var coordinator: MainCoordinator?
var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    let navController = UINavigationController()
    coordinator = MainCoordinator(navigationController: navController)
    coordinator?.start()

    window = UIWindow(frame: UIScreen.main.bounds)
    window?.rootViewController = navController
    window?.makeKeyAndVisible()

    return true
}

我看到现在window 在 SceneDelegate 中,但是将那里的所有内容移到 sceneDidConnect 方法没有帮助。 有人可以在这里启发我吗?

谢谢!

【问题讨论】:

    标签: ios swift appdelegate coordinator-pattern


    【解决方案1】:

    因此必须进行一些更改才能实现此模式。首先,您应该将 AppDelegate 恢复为创建时的初始格式:

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        return true
    }
    

    您可以删除顶部的var coordinator: MainCoordinator? 声明。

    SceneDelegate 中,将sceneWillConnectToSession 函数中的代码替换为以下内容:

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { 
        guard let windowScene = (scene as? UIWindowScene) else { return }
        let navController = UINavigationController()
        let coordinator = MainCoordinator(navigationController: navController)
        coordinator.start()
    
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = navController
        self.window = window
        window.makeKeyAndVisible()
    }
    

    最后的改变是我在你的视图控制器中删除了MainCoordinator 的弱声明。

    所以我只是将它替换为var coordinator: MainCoordinator?,然后它就起作用了。

    Reference Article: The Scene Delegate In Xcode 11 And iOS 13

    【讨论】:

    • 你试过运行代码吗?我应用了您的编辑,它的行为与以前完全一样...我已经进入主屏幕,但按钮没有导航...
    • 是的,很抱歉,我认为问题是由于某种原因没有加载视图控制器。我发现代码的问题是,您正在创建的 UIWindow 实际上从未被设为 keyAndVisible。您可以通过检查在 MainCoordinator 中创建的 VC 的内存地址与您尝试断点 @IBAction 函数之一时存在的内存地址来确认这一点。我会尽快编辑
    • 不错!有用!我只是在windowself.window 部分之前避开了let,因为SceneDelegate 已经有一个var window: UIWindow?。谢谢!
    • 这似乎是我在 XCode 12 中最接近可行的解决方案(哦,我多么讨厌 XCode),当使用基本骨架运行时,我在控制台中收到以下警告:[WindowScene] Failed to instantiate the default view controller for UIMainStoryboardFile 'Main' - perhaps the designated entry point is not set?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    • 1970-01-01
    相关资源
    最近更新 更多