gpt4 book ai didi

ios - 如何根据条件更改应用程序的颜色主题?

转载 作者:可可西里 更新时间:2023-11-01 01:56:06 25 4
gpt4 key购买 nike

我正在尝试寻找更改应用颜色主题的最佳方法。在我的调查之后,我启发了 Durul Dalkanat 在 https://medium.com/@duruldalkanat/part-2-installing-theme-manager-18a32c314cf1 上的帖子并编写了以下代码以应用于我的应用。

我的问题是当用户切换开关按钮时颜色主题没有改变。

如有必要,请详细说明

我创建了一个包含我的颜色的枚举。

enum ColorTheme: Int {
case day, night

var mainColor:UIColor {
switch self {
case .day:
return UIColor().hexToUIColor("D9D8C8")
case .night:
return UIColor().hexToUIColor("141B1B")

}
}}

然后我创建了一个结构,以便将我的颜色主题应用到我的应用程序中的所有组件,并设置为用户默认值并从那里获取,如下所示。

let selectedThemeKey = "SelectedTheme"

struct ThemeManager {

static func currentTheme() -> ColorTheme {

if let storedTheme = (UserDefaults.standard.value(forKey: selectedThemeKey) as AnyObject).integerValue {
return ColorTheme(rawValue: storedTheme)!
} else {
return .night
}
}

static func applyTheme(theme:ColorTheme){

UserDefaults.standard.set(theme.rawValue, forKey: selectedThemeKey)
UserDefaults.standard.synchronize()

UITabBar.appearance().backgroundColor = currentTheme().mainColor
}}

然后我将我的代码添加到AppDelegate 中的 didFinishLaunchWithOptions 方法

let defaultTheme = ThemeManager.currentTheme()

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.

let defaultTheme = ThemeManager.currentTheme()
ThemeManager.applyTheme(theme: defaultTheme)
return true

}

最后,我向我的 SettingViewController 添加了一个 UISwitch 来更改我的颜色主题,我想在其操作中管理我的颜色主题,如下所示。

let appDelegate = UIApplication.shared.delegate as! AppDelegate

@IBAction func colorModeSwitchSwiped(_ sender: UISwitch) {


if colorModeSwitch.isOn {
ThemeManager.applyTheme(theme: ColorTheme.day)

}else {
ThemeManager.applyTheme(theme: ColorTheme.night)

}

}

此代码在 ViewController 中有效,可在我切换时更改 View 背景颜色,但必须重新启动应用程序才能更改 UITabBar 颜色。颜色不会像我在 ViewControllers 中定义的那样同时改变。 View Controller 示例;

override func viewWillAppear(_ animated: Bool) {
self.view.backgroundColor = ThemeManager.currentTheme().mainColor
}

如何解决这个问题?什么是正确的做法?

最佳答案

看看 documentationUIAppearance 中,有一条注释说:

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.

因此,如果您通过其外观代理设置标签栏颜色,则不会更改它,因为它已经在 View 层次结构中。你需要直接设置它:

tabBar.tintColor = ThemeManager.currentTheme().mainColor

关于ios - 如何根据条件更改应用程序的颜色主题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53393277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com