我正在尝试为我的应用程序应用深色主题,当我调用深色主题时遇到问题,代码在重新启动应用程序之前不起作用。
我在设置 View Controller 中使用 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)
}
最佳答案
将内容保存到UserDefaults
不会立即发生。解决此问题的方法是仅在开始时从 UserDefaults
获取 darkMode
的值。
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
}
关于ios - 使用代码更改 UITabbar 外观,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51897810/