设置UINavigationBar全局外观后,推送UISearchController时导航栏与搜索栏变黑问题咨询
问题原因
这个黑色导航栏与搜索页渲染异常的核心原因是iOS13之后导航栏外观机制的变更:
你在AppDelegate里通过UINavigationBar.appearance()设置的零散属性,只会应用到应用启动阶段已经初始化完成的导航栏实例。当你触发UISearchController进入搜索状态时,系统会动态新建一个临时的导航栏实例来承载搜索输入控件,这个新实例不会自动继承你之前设置的全局外观配置。
再加上你显式设置了isTranslucent = false开启导航栏不透明模式,没有配置自定义背景色的不透明导航栏,在系统默认渲染逻辑下就会显示为纯黑色,连带把下方的搜索控制器内容区域也衬成黑色。
可落地的解决方案
根据你的适配版本选对应方案即可:
- iOS13+ 适配(推荐,一次配置全场景生效)
放弃旧的零散appearance属性配置,改用iOS13推出的UINavigationBarAppearance做统一样式配置,这套配置会自动同步到所有由系统动态创建的导航栏实例(包括搜索场景的临时导航栏),替换掉你AppDelegate里原来的旧配置即可:if #available(iOS 13.0, *) { // 初始化不透明导航栏的外观配置 let navBarAppearance = UINavigationBarAppearance() navBarAppearance.configureWithOpaqueBackground() navBarAppearance.backgroundColor = UIColor(hex: "E1354A") navBarAppearance.titleTextAttributes = [.foregroundColor: UIColor.white] // 统一设置导航栏的按钮 tint 颜色 UINavigationBar.appearance().tintColor = .white // 把外观配置应用到所有导航栏场景,包括滚动到边缘、搜索激活的场景 UINavigationBar.appearance().standardAppearance = navBarAppearance UINavigationBar.appearance().scrollEdgeAppearance = navBarAppearance } else { // 低版本iOS保留你原来的配置即可 UINavigationBar.appearance().barTintColor = UIColor(hex: "E1354A") UINavigationBar.appearance().tintColor = .white UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white] UINavigationBar.appearance().isTranslucent = false } - 临时快速修复(如果暂时不想重构全局配置)
在你初始化UISearchController的地方,手动给搜索栏补对应的颜色配置,抵消系统默认的黑色渲染:let searchController = UISearchController(searchResultsController: nil) // 强制搜索栏使用和导航栏一致的背景色 searchController.searchBar.barTintColor = UIColor(hex: "E1354A") searchController.searchBar.tintColor = .white // 关闭搜索时的背景模糊遮罩,避免和不透明导航栏的视觉效果冲突 searchController.obscuresBackgroundDuringPresentation = false - 额外注意:如果你是把searchController绑定到导航项上,记得显式关闭系统自动的边缘外观适配,避免大标题模式下导航栏颜色跳变:
if #available(iOS 11.0, *) { navigationItem.searchController = searchController navigationItem.hidesSearchBarWhenScrolling = false }
内容的提问来源于stack exchange,提问作者Parcker。
相关产品推荐
相关产品推荐

