升级Xcode11.3.1并重构Storyboard后导航栏及视图消失求助
解决直接设置ViewController为入口时导航栏消失的问题
看起来你遇到的核心问题是:当把目标ViewController直接设为应用入口时,它没有被嵌入到UINavigationController中,而之前作为子VC时,它处于导航栈的上下文里,所以导航栏能正常渲染。下面是具体的解决步骤:
1. 确保目标VC被包裹在UINavigationController中
方式一:通过Storyboard设置
- 打开你的Storyboard,拖入一个
UINavigationController组件。 - 选中这个Navigation Controller的
Root View Controller,右键拖拽连接到你的目标ViewController,选择"Set Root View Controller"。 - 最后勾选Navigation Controller的
Is Initial View Controller(在Attributes Inspector面板中),将它设为应用的入口。
方式二:通过代码设置(SceneDelegate)
如果你的应用用代码配置窗口,修改SceneDelegate.swift中的scene(_:willConnectTo:options:)方法:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard let windowScene = (scene as? UIWindowScene) else { return } let window = UIWindow(windowScene: windowScene) // 初始化你的目标ViewController(如果从Storyboard加载,用instantiateViewController(withIdentifier:)) let targetVC = YourTargetViewController(nibName: nil, bundle: nil) // 用NavigationController包裹目标VC let navController = UINavigationController(rootViewController: targetVC) // 开启大标题偏好(确保大标题能正常显示) navController.navigationBar.prefersLargeTitles = true window.rootViewController = navController self.window = window window.makeKeyAndVisible() }
2. 完善导航栏配置代码
在你的UINavigationController扩展中,建议加上prefersLargeTitles的设置,确保大标题模式生效:
extension UINavigationController { func set_iOS12_lookAndFeel() { self.navigationBar.prefersLargeTitles = true // 新增这一行 if #available(iOS 13.0, *) { self.keep_iOS12_lookAndFeel() } else { let attrLargeTitle = AppConstants.FontAttributes.NavBar_LargeTitleTextAttributes self.navigationBar.largeTitleTextAttributes = attrLargeTitle let attrTitle = AppConstants.FontAttributes.NavBar_TitleTextAttributes self.navigationBar.titleTextAttributes = attrTitle } } // ... 原有的keep_iOS12_lookAndFeel方法保持不变 }
为什么之前作为子VC时正常?
当目标VC作为其他ViewController的子VC时,那个父VC大概率处于UINavigationController的导航栈里,所以目标VC能通过navigationController拿到有效的实例,导航栏的配置代码能生效。但直接作为入口时,VC没有被导航控制器托管,navigationController?是nil,所有针对导航栏的设置都不会起作用,自然就看不到导航栏了。
按照上面的步骤调整后,你的目标VC会被正确嵌入导航控制器,导航栏应该就能正常显示大标题和自定义样式了。
内容的提问来源于stack exchange,提问作者iKK
相关产品推荐
相关产品推荐

