无法在 AppDelegate 中以编程方式将 viewContoller 添加到选项卡栏
Can't add viewContoller to Tab Bar programmatically in the AppDelegate
我正在尝试通过 didFinishLaunchWithOptions
以编程方式将 viewController 添加到现有选项卡栏,但我的代码不起作用,我无法将 rootViewController 向下转换为 UITabBarController。
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
if let tabBarController = window?.rootViewController as? UITabBarController {
print("rootVC")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "NavController")
vc.tabBarItem = UITabBarItem(tabBarSystemItem: .topRated, tag: 1)
tabBarController.viewControllers?.append(vc)
}
return true
}
这是我的故事板,我觉得这里没问题,Tab Bar Contoller 是初始视图控制器...
Main.storyboard
在 iOS 13+ 中,应用程序委托中的 didFinishLaunchingWithOptions
中的 window 将为零。而是将代码移动到 SceneDelegate
:
中的 willConnectTo session
方法
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
if let tabBarController = window?.rootViewController as? UITabBarController {
print("rootVC")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "NavController")
vc.tabBarItem = UITabBarItem(tabBarSystemItem: .topRated, tag: 1)
tabBarController.viewControllers?.append(vc)
}
guard let _ = (scene as? UIWindowScene) else { return }
}
我正在尝试通过 didFinishLaunchWithOptions
以编程方式将 viewController 添加到现有选项卡栏,但我的代码不起作用,我无法将 rootViewController 向下转换为 UITabBarController。
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
if let tabBarController = window?.rootViewController as? UITabBarController {
print("rootVC")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "NavController")
vc.tabBarItem = UITabBarItem(tabBarSystemItem: .topRated, tag: 1)
tabBarController.viewControllers?.append(vc)
}
return true
}
这是我的故事板,我觉得这里没问题,Tab Bar Contoller 是初始视图控制器...
Main.storyboard
在 iOS 13+ 中,应用程序委托中的 didFinishLaunchingWithOptions
中的 window 将为零。而是将代码移动到 SceneDelegate
:
willConnectTo session
方法
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
if let tabBarController = window?.rootViewController as? UITabBarController {
print("rootVC")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "NavController")
vc.tabBarItem = UITabBarItem(tabBarSystemItem: .topRated, tag: 1)
tabBarController.viewControllers?.append(vc)
}
guard let _ = (scene as? UIWindowScene) else { return }
}