如果用户名= = nil,我想在tabbar中更改 viewControllers 。
我有两个可以更改的viewControllers:
1) ProfileVC
2) SignInVC
但是当我的应用程序启动时,用户会看到不同的viewController,他是 NewsVC 。
我需要在运行应用程序之前进行检查,并在tabbar中替换viewController。
在AppDelegate.swift中大致如此:
let storyboard = UIStoryboard(name: "Main", bundle: nil)
if Auth.auth().currentUser != nil {
let profileVC = storyboard.instantiateViewController(withIdentifier: "ProfileVC")
window?.rootViewController = profileVC
} else {
let loginVC = storyboard.instantiateViewController(withIdentifier: "SignInVC")
window?.rootViewController = loginVC
}
}
但这不正确。我怎么改变索引或viewController?
答案 0 :(得分:0)
您需要继承UITabBarController
并管理它的viewControllers
数组
class MainTabBarController: UITabBarController {
override func awakeFromNib() {
super.awakeFromNib()
// if you will say force - unwrapped it's the developer job to keep track here
let signUp = self.viewControllers![0]
let profile = self.viewControllers![1]
let newsFeeds = self.viewControllers![2]
if user == nil {
self.viewControllers = [signUp] // leave signup only
}
}
}
将MainTabBarController
分配给IB
答案 1 :(得分:-1)
您需要为viewcontroller设置索引。
这是你以编程方式执行的方式:
self.window = UIWindow(frame: UIScreen.main.bounds)
let nav1 = UINavigationController()
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let profileVC = mainStoryboard.instantiateViewController(withIdentifier: "ProfileVC") as! //your VC
nav1.viewControllers = [profileVC]
let nav2 = UINavigationController()
let loginVC = mainStoryboard.instantiateViewController(withIdentifier: "SignInVC") as! //Your VC
nav2.viewControllers = [loginVC]
let tabController = UITabBarController()
tabController.viewControllers = [profileVC, loginVC]
tabController.selectedIndex = 0 //This line will solve your question & take you to the profileVC
self.window!.rootViewController = tabController
self.window?.makeKeyAndVisible()