【问题标题】:Xcode 11 beta: AppDelegate file doesn't have window global variableXcode 11 beta:AppDelegate 文件没有窗口全局变量
【发布时间】:2023-10-17 20:24:01
【问题描述】:

我在 Xcode 11 测试版中遇到问题。

问题是我没有在AppDelegate 文件中声明默认的window 变量。

有人遇到同样的问题吗?

【问题讨论】:

  • 这给您带来了什么问题?
  • 我使用的是 Xcode 11 beta,只是我创建了单视图应用程序。在 AppDelegate 文件中没有对象调用窗口。而我们在以前的 Xcode 版本中就有它。
  • 再说一次,这给您带来了什么问题?
  • 我想使用 window 变量来设置 rootViewController。这有意义吗?
  • UIApplicationDelegate 已经定义了 window 属性。 UIApplication.shared.delegate?.window.

标签: xcode uikit appdelegate uiwindow


【解决方案1】:

在 Xcode 11 中,这现在在 SceneDelegate 中完成

编辑:如果您仍然支持 iOS 12 或更早版本(或想要支持 13 及之前版本)

UIWindowSceneDelegate 添加到ApplicationDelegate

添加:var window:UIWindow?

然后按照您在didFinishLaunching中的设置进行操作

【讨论】:

  • 是的,但是如果您的新项目的目标是 iOS11 或 iOS12 怎么办?那么该行需要在AppDelegate 中。
  • 你找到解决办法了吗?
【解决方案2】:

默认的 var 窗口:UIWindow?现在在 SceneDelegate.swift 中移动。要在 Xcode 11 中设置 rootViewController,您可以在 SceneDelegate.swift 文件中工作,在场景委托中,您必须创建窗口实例和根视图控制器,如下所示:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

        // set or create your viewController here
        let yourViewController = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(identifier: "yourViewController") as! YourViewController
        // set the rootViewController here using window instance
        self.window?.rootViewController = yourViewController
    }

这个答案也很有帮助:Why is manually setup root view controller showing black screen?

希望对你有帮助!

【讨论】:

  • 这个函数写的时候只能在iOS 13中使用
【解决方案3】:

我的做法:

首先,在 AppDelegate 中使用您要访问的视图控制器的类创建一个静态属性,如下所示

class AppDelegate: UIResponder, UIApplicationDelegate {

    // MARK: Home
    static var homeViewController: HomeViewController?

    ...
}

然后,在视图控制器中

// MARK: - Managing the view
override func viewDidLoad() {
    super.viewDidLoad()

    // Singleton
    AppDelegate.homeViewController = self

    ...
}

使用方法:

extension UIViewController {
    var homeViewController: HomeViewController? {
        if let controller = self as? HomeViewController {
            return controller
        }

        return AppDelegate.homeViewController
    }
}

【讨论】:

    【解决方案4】:

    就我而言,仅此而已。

        var window: UIWindow? // add this by yourself
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    
            window = UIWindow(frame: Device.bounds)
            let root = DDTabBarController()
            window?.rootViewController = root
            window?.makeKeyAndVisible()
            return true
        }
    

    【讨论】: