我正在尝试为应用程序应用深色主题,当我调用深色主题时遇到问题,直到重新启动应用程序,代码才起作用。
我在设置视图控制器中使用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)
}
答案 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
}