繁体   English   中英

重新加载 AppDelegate

[英]Reloading AppDelegate

在 AppDelegate 我有应用程序颜色:

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    let defaults = UserDefaults.standard
    let switchState = defaults.integer(forKey: "switchState")
    if switchState == 1 {
        UINavigationBar.appearance().barTintColor = UIColor.black
        UIApplication.shared.statusBarStyle = .lightContent
        UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white]
        UITabBar.appearance().barTintColor = UIColor.black
        UISearchBar.appearance().barStyle = UIBarStyle.black
        UITextField.appearance().keyboardAppearance = UIKeyboardAppearance.dark
    }
    window = UIWindow(frame: UIScreen.main.bounds)
    window?.makeKeyAndVisible()
    return true
}

这样滑块就会打开“暗模式”。 但要使更改生效,必须重新启动应用程序。 如何在不重新启动应用程序的情况下执行此操作?

您可以简单地将颜色逻辑移动到一个函数,然后在需要时调用该函数。

因此,您在类中创建了这样的函数:

static func setColorsOfApp()
{
    let defaults = UserDefaults.standard
    let switchState = defaults.integer(forKey: "switchState")
    if switchState == 1 {
        UINavigationBar.appearance().barTintColor = UIColor.black
        UIApplication.shared.statusBarStyle = .lightContent
        UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white]
        UITabBar.appearance().barTintColor = UIColor.black
        UISearchBar.appearance().barStyle = UIBarStyle.black
        UITextField.appearance().keyboardAppearance = UIKeyboardAppearance.dark
    }
}

然后像这样调用这个函数:

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

以及您想要的任何其他地方。

粗略查看application:didFinishLaunchingWithOptions:的文档会发现该函数在启动时显式运行一次。 您是否考虑过将此代码从该函数中移出并移至其他一些可以更自由调用的方法中?

Google 了解UISwitch工作原理,并从回调中调用 Ayush 的函数,以便您的应用“立即将 UI 更改为暗色”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM