首页 > 解决方案 > 导航栏颜色更改未通过 UINavigationBarAppearance() 传递到其他视图

问题描述

我正在尝试在 Xcode 12.5.1 中解决这个问题,以便我可以迁移到 Xcode 13。我已经在 Xcode 13 Released 中运行了这个应用程序,这就是我发现问题的方式。我知道我玩游戏有点晚了,但在 Xcode 13 之前……它并没有被破坏。

在我的应用程序中,我在夏季、秋季和冬季三种配置中设置了自定义主题。每个主题设置导航栏的颜色属性以及应用程序中其他控件的颜色属性。主题是从分段控件的设置 VC 中选择的。

setNavbarAttributes() 代码在 didFinishLaunchingWithOptions 中从 AppDelegate 运行。它在应用程序启动时设置正确的 navBar 属性。在这种情况下,代码按预期工作。我可以通过导航到应用程序中的其他视图并观察导航栏显示正确的颜色属性来验证这一点。

当从设置 VC 上的分段控件中选择主题时,setNavbarAttributes() 代码也会运行。这就是问题所在。更改主题时,导航栏颜色属性不会传递到其他视图中的导航栏。有谁知道为什么这不起作用?通过将设置 VC 更新代码放在扩展中,我有一个不太好的解决方法,但这意味着要触及每个 VC。这似乎不对。

它适用于下面显示的旧代码,但在 Xcode 13 中使用 UINavigationBarAppearance() 被破坏了。

let theNavebarProperties = UINavigationBar.appearance()
theNavebarProperties.barTintColor = Theme.current.navbarColor
theNavebarProperties.isTranslucent = false
theNavebarProperties.titleTextAttributes = [.foregroundColor: Theme.current.accentColor, .font: UIFont.systemFont(ofSize: gNavBarTitleTextSize, weight: .semibold)]

这会设置应用程序中导航栏的属性。

class SetNarbar
{
    static func setNavbarAttributes()
    {
        let theAppearance = UINavigationBarAppearance()

        theAppearance.configureWithOpaqueBackground()
        theAppearance.backgroundColor = Theme.current.navbarColor
        theAppearance.titleTextAttributes = [.foregroundColor: Theme.current.accentColor, .font:  UIFont.systemFont(ofSize: gNavBarTitleTextSize, weight: .semibold)]
        
        UINavigationBar.appearance().standardAppearance = theAppearance
        UINavigationBar.appearance().scrollEdgeAppearance = theAppearance
        UINavigationBar.appearance().compactAppearance = theAppearance
    }
}

此代码在 viewDidLoad 上的设置 VC 中以及在点击主题选择器时运行。

// Sets the controls on the settings VC to the currently selected theme. I have omitted code that works and does not pertain to setting the navBar.
    func updateThemeOnSettingsVC()
    {
        setNeedsStatusBarAppearanceUpdate()
        
        SetNarbar.setNavbarAttributes()
        
        let navAppearance = UINavigationBarAppearance()
        navAppearance.configureWithOpaqueBackground()
        navAppearance.backgroundColor = Theme.current.navbarColor
        navAppearance.titleTextAttributes = [.foregroundColor: Theme.current.accentColor, .font:  UIFont.systemFont(ofSize: gNavBarTitleTextSize, weight: .semibold)]
        navigationItem.standardAppearance = navAppearance
        navigationItem.scrollEdgeAppearance = navAppearance
        navigationItem.compactAppearance = navAppearance
    }

标签: iosswiftuinavigationbarxcode12.5

解决方案


推荐阅读