使用代码更改UITabbar外观

时间:2018-08-17 14:42:44

标签: ios iphone swift uitabbarcontroller uitabbar

我正在尝试为应用程序应用深色主题,当我调用深色主题时遇到问题,直到重新启动应用程序,代码才起作用。 我在设置视图控制器中使用UISwtich调用暗模式。当我打开暗模式时,print日志将被调用。 这是代码:

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


 NotificationCenter.default.addObserver(self, selector: #selector(darkTheme), name: NSNotification.Name("DARKTHEME"), object: nil)
        darkTheme()

     return true 

}


       @objc func darkTheme()  {

            if appDefaults.darkTheme() == true {

              print("dark mode")

                UITabBar.appearance().barTintColor = UIColor(red:0.16, green:0.16, blue:0.16, alpha:1.00)
                UITabBar.appearance().tintColor = UIColor(red:0.16, green:0.16, blue:0.16, alpha:1.00)

                UITabBar.appearance().isTranslucent = false
                UIApplication.shared.statusBarStyle = .lightContent

            } else {

           print("white mode")

                UITabBar.appearance().barTintColor = UIColor.white
                UITabBar.appearance().tintColor = UIColor.white

                UIApplication.shared.statusBarStyle = .default
                UITabBar.appearance().isTranslucent = true

            }
        }

已编辑:

    //MARK: - Black Theme
    func setDarkTheme(enable:Bool)  {
        UserDefaults.standard.set(enable, forKey: "Dark")
    }

    func darkTheme() -> Bool {
        return UserDefaults.standard.bool(forKey: "Dark")
    }


   @objc func darkMode(_ sender:UISwitch) {



        if sender.isOn {
            appDefaults.setDarkTheme(enable: true)
            print("DARK THEME ON")
        } else {
            appDefaults.setDarkTheme(enable: false)
            print("DARK THEME OFF")
        }

        NotificationCenter.default.post(name: NSNotification.Name("DARKTHEME"), object: nil)

    }

1 个答案:

答案 0 :(得分:0)

将事情保存到UserDefaults不会立即发生。一种解决方法是,一开始只从darkMode获得UserDefaults的值。

var shouldChangeUserDefaults = false

var darkMode: Bool {
    didSet {
        if shouldChangeUserDefaults {
            UserDefaults.standard.set(darkMode, forKey: "Dark")
        }
    }
}

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

    darkMode = UserDefaults.standard.bool(forKey: "Dark")
    shouldChangeUserDefaults = true

    return true
}