如何通过用户变量控制UI标签栏外观

时间:2019-05-18 23:35:14

标签: ios uitabbar appearance programmatically

我的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
    }

这有效,但效果很差。重新启动应用程序后,它只能更改标签栏的颜色。我想让它更直接。放置控件的位置选择似乎有限 到应用程序委托。我想控制我的标签栏颜色 而是主程序区域。

1 个答案:

答案 0 :(得分:0)

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

  

iOS会在视图进入窗口时应用外观更改,但不会   更改窗口中已有视图的外观。改变   当前在窗口中的视图的外观,请删除该视图   然后从视图层次结构中放回去。

     

参考:https://developer.apple.com/documentation/uikit/uiappearance


解决方案:

呈现并关闭虚拟UIViewController。从而刷新窗口的可见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)
}