如何从我的用户变量控制 UI 选项卡栏外观

How can I control UI Tab Bar Appearance from my user variables

我的 IOS 标签栏应用有明亮和黑暗两种显示模式。为了使这项工作顺利进行, 我想根据显示模式相应地设置标签栏外观。我有以下 执行此操作的代码。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {


        displayMode=UserDefaults.standard.integer(forKey: "displayMode")

        if displayMode==0 // bright display. want bright tab bar
        {   UITabBar.appearance().backgroundColor=UIColor.white
            UITabBar.appearance().barTintColor=UIColor.white
            UITabBar.appearance().unselectedItemTintColor = UIColor.darkGray
            UITabBar.appearance().tintColor = UIColor.blue
            UITabBar.appearance().isTranslucent = false
        }

        if displayMode==1 // dark display. want dark tab bar
        {   UITabBar.appearance().backgroundColor=UIColor.black
            UITabBar.appearance().barTintColor=UIColor.black
            UITabBar.appearance().unselectedItemTintColor = UIColor.lightGray
            UITabBar.appearance().tintColor = UIColor.white
            UITabBar.appearance().isTranslucent = false
        }

        return true
    }

这很有效,但效果不佳。它只能在应用程序重新启动时更改选项卡栏颜色。我想让它更直接。放置控件的位置选择似乎有限 给 App Delegate。我想从我的控制标签栏颜色 改为主程序区。

Appearance代理不限AppDelegate。您可以随时随地应用它,但请注意以下事项:

iOS applies appearance changes when a view enters a window, it doesn’t change the appearance of a view that’s already in a window. To change the appearance of a view that’s currently in a window, remove the view from the view hierarchy and then put it back.

Ref: https://developer.apple.com/documentation/uikit/uiappearance


解决方案:

展示和解散一个假人UIViewController。从而刷新window.

的可见viewController

示例:

func randomTabBarAppearance() {
    UITabBar.appearance().backgroundColor = UIColor.init(red: CGFloat.random(in: 0...1),
                                                         green: CGFloat.random(in: 0...1),
                                                         blue: CGFloat.random(in: 0...1),
                                                         alpha: 1)

    present(UIViewController(), animated: false, completion: nil)
    dismiss(animated: false, completion: nil)
}