2017-01-21 84 views
-1

在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 
} 

使滑塊打開「暗模式」。但要使更改生效,應用程序必須重新啓動。如何在不重新啓動應用程序的情況下執行此操作?

回答

1

您可以簡單地將顏色邏輯移至某個函數,然後在需要時調用該函數。

所以,你讓這樣的功能在你的類:

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 
} 

和其他地方你想要的。

+0

我想滑塊一旦打開立即更改UI暗。 –

0

粗略瀏覽application:didFinishLaunchingWithOptions:的文檔可以發現該函數在啓動時顯式運行一次。你有沒有考慮過把這個代碼移出這個函數,並轉換成其他可以更自由地調用的方法?

谷歌如何UISwitch工作,並從回調調用AYUSH的功能,使您的應用程序將「立即更改UI暗」

+0

是的,我知道'application:didFinishLaunchingWithOptions:'的作用,現在當滑塊打開時,一個UIAlertController顯示,要求用戶重新啓動應用程序。 –