You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

iOS 13导航栏默认隐藏,如何恢复带标题的旧版导航栏样式?

Hey Tyler, 我刚搞定过iOS 13带来的导航栏样式兼容问题,这就给你几个实用方案把它恢复到旧版的样子:

方案1:全局统一设置旧版导航栏样式

如果你想让整个APP的导航栏都回到旧版样式,可以在AppDelegate或者SceneDelegate的启动方法里配置:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // 适配iOS 13及以上系统
    if #available(iOS 13.0, *) {
        let navBarAppearance = UINavigationBarAppearance()
        // 配置不透明背景(和旧版导航栏一致)
        navBarAppearance.configureWithOpaqueBackground()
        // 设置导航栏背景色,这里用旧版默认的蓝色,你可以换成自己需要的颜色
        navBarAppearance.backgroundColor = .systemBlue
        // 设置标题文字样式,和旧版一致的白色文字
        navBarAppearance.titleTextAttributes = [.foregroundColor: UIColor.white]
        navBarAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white]
        
        // 给导航栏的三种状态都应用这个样式
        UINavigationBar.appearance().standardAppearance = navBarAppearance
        UINavigationBar.appearance().scrollEdgeAppearance = navBarAppearance
        UINavigationBar.appearance().compactAppearance = navBarAppearance
    } else {
        // iOS 13之前的系统保持原有配置即可
        UINavigationBar.appearance().barTintColor = .systemBlue
        UINavigationBar.appearance().titleTextAttributes = [.foregroundColor: UIColor.white]
        UINavigationBar.appearance().isTranslucent = false
    }
    return true
}
方案2:针对单个导航控制器自定义样式

如果只是某个特定页面的导航栏需要恢复旧版样式,可以在对应的ViewController里设置:

override func viewDidLoad() {
    super.viewDidLoad()
    
    if #available(iOS 13.0, *) {
        let navBarAppearance = UINavigationBarAppearance()
        navBarAppearance.configureWithOpaqueBackground()
        navBarAppearance.backgroundColor = .systemBlue
        navBarAppearance.titleTextAttributes = [.foregroundColor: UIColor.white]
        
        // 给当前导航控制器的导航栏应用样式
        navigationController?.navigationBar.standardAppearance = navBarAppearance
        navigationController?.navigationBar.scrollEdgeAppearance = navBarAppearance
    } else {
        navigationController?.navigationBar.barTintColor = .systemBlue
        navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.white]
        navigationController?.navigationBar.isTranslucent = false
    }
}
几个容易踩坑的关键点
  • 必须设置scrollEdgeAppearance:iOS 13之后,当页面滚动到顶部时,导航栏会使用scrollEdgeAppearance的样式,如果不设置,就会变成透明状态,这是很多人觉得导航栏“消失”的核心原因。
  • 如果你想要旧版的半透明模糊背景,可以把configureWithOpaqueBackground()换成configureWithDefaultBackground(),同时保持isTranslucent = true,再调整backgroundColor为半透明颜色即可。
  • 检查是否有代码手动隐藏了导航栏:比如navigationController?.isNavigationBarHidden = true,如果有记得移除或者调整逻辑。

内容的提问来源于stack exchange,提问作者Tyler Rutt

火山引擎 最新活动