Swift 5 & Xcode 11
在xCode 11中,appDelegate中的窗口解决方案已不再有效。他们将其移动到了SceneDelgate中。您可以在SceneDelgate.swift文件中找到它。
您会注意到现在有一个var window:UIWindow?
。
在我的情况下,我正在使用来自storyboard的TabBarController,并希望将其设置为rootViewController。
这是我的代码:
sceneDelegate.swift
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
self.window = self.window ?? UIWindow()
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let tabBarController = storyboard.instantiateViewController(withIdentifier: "tabBarController") as! UITabBarController
for child in tabBarController.viewControllers ?? [] {
if let top = child as? StateControllerProtocol {
print("State Controller Passed To:")
print(child.title!)
top.setState(state: stateController)
}
}
self.window!.rootViewController = tabBarController
self.window!.makeKeyAndVisible()
print("Finished scene setting code")
guard let _ = (scene as? UIWindowScene) else { return }
}
请确保像我这样将其添加到正确的场景方法中。注意,在storyboard中使用的tabBarController或viewController需要设置“标识符名称”。
在我的情况下,我是为了设置stateController以跟踪选项卡视图之间共享变量而执行此操作。如果您想要执行相同的操作,请添加以下代码...
StateController.swift
import Foundation
struct tdfvars{
var rbe:Double = 1.4
var t1half:Double = 1.5
var alphaBetaLate:Double = 3.0
var alphaBetaAcute:Double = 10.0
var totalDose:Double = 6000.00
var dosePerFraction:Double = 200.0
var numOfFractions:Double = 30
var totalTime:Double = 168
var ldrDose:Double = 8500.0
}
protocol StateControllerProtocol {
func setState(state: StateController)
}
class StateController {
var tdfvariables:tdfvars = tdfvars()
}
注意:只需使用您自己的变量或想要跟踪的任何内容,我只是在tdfvariables结构中列出了我的示例。
在TabController的每个视图中添加以下成员变量。
class SettingsViewController: UIViewController {
var stateController: StateController?
.... }
然后在同样的文件中添加以下内容:
extension SettingsViewController: StateControllerProtocol {
func setState(state: StateController) {
self.stateController = state
}
}
这样做的作用是允许您避免在视图之间传递变量时采用单例模式的方式。这有利于采用依赖注入模型,长期来看比单例模式更好。