Swift开发:注册账号跳转首页后tab bar与navigation controller消失问题
问题原因
- 你的代码直接单独实例化并弹出了
HomeFeedViewController,这个页面本身没有嵌套在你预设的导航控制器、Tab Bar控制器层级中,自然不会显示顶部导航栏和底部Tab Bar。 - 冷启动APP时会走Main.storyboard的初始控制器(即你配置的Tab Bar控制器)加载逻辑,Tab Bar会自动加载关联的所有子模块(包括Home模块的导航控制器+HomeFeedViewController),所以重启后显示正常。
修复方案
推荐使用替换根控制器的方案,符合注册登录完成后无需返回登录注册页的常规业务逻辑:
if success { // 实例化Main.storyboard的初始控制器(也就是你预设的Tab Bar控制器) let mainSB = UIStoryboard(name: "Main", bundle: nil) guard let mainTabBar = mainSB.instantiateInitialViewController() else { return } // 替换当前window的根控制器 if let window = UIApplication.shared.connectedScenes .filter({$0.activationState == .foregroundActive}) .compactMap({$0 as? UIWindowScene}) .first?.windows .first(where: \.isKeyWindow) { window.rootViewController = mainTabBar window.makeKeyAndVisible() // 可选添加过渡动画避免生硬跳转 UIView.transition(with: window, duration: 0.3, options: .transitionCrossDissolve, animations: nil) } print("successfully registered") } else { let validationAlert = UIAlertController(title: "Sign Up Failed", message: "There was an error registering your account. Please try again.", preferredStyle: .alert) validationAlert.addAction(UIAlertAction(title: "Cool", style: .cancel, handler: nil)) self.present(validationAlert, animated: true) }
如果你确实需要模态弹出带Tab Bar的首页,也可以直接弹出Tab Bar控制器而非单独的HomeFeedViewController:
if success { let mainSB = UIStoryboard(name: "Main", bundle: nil) guard let mainTabBar = mainSB.instantiateInitialViewController() else { return } mainTabBar.modalPresentationStyle = .fullScreen self.present(mainTabBar, animated: true) print("successfully registered") }
补充注意
你原来的代码加载的是名为HomeFeed的storyboard,即便你要单独加载Home模块,也需要实例化Home.storyboard的初始导航控制器再弹出,才能保证顶部导航栏正常显示,但这种方式还是不会携带Tab Bar,不符合你的需求。
内容的提问来源于stack exchange,提问作者jo1
相关产品推荐
相关产品推荐

