3

I want to support 2 themes for an app. Light and Dark one. So, I have a UIButton that allows the user to tap on it and switch between light and dark theme.

The UITabBar has it's own class and I've set it to change accordingly to the current theme but it's not working. Not sure what I'm doing wrong.

class MainTabbar: UITabBarController {

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.tabBar.barTintColor = Theme.current.tabbarTintColor
        self.tabBar.tintColor = Theme.current.tabbarSelectedItems
        self.tabBar.unselectedItemTintColor = Theme.current.tabbarUnselectedItemsColor
    }
}

In the AppDelegate file, I check whether there's a selected theme if not, set the LightTheme.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
 // Set Theme
 if UserDefaults.standard.object(forKey: SelectedThemeKey) != nil {
        Theme.current = UserDefaults.standard.bool(forKey: SelectedThemeKey) ? LightTheme() : DarkTheme()
        print("current theme is: \(Theme.current)")
    }
 }

As of now, it only changes the colors of the UITabbar IF the app is being relaunched.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Dani
  • 3,427
  • 3
  • 28
  • 54

1 Answers1

3

When the app theme is changed you need to access these anywhere either inside any tab

self.tabBarController.tabBar.barTintColor = Theme.current.tabbarTintColor
self.tabBarController.tabBar.tintColor = Theme.current.tabbarSelectedItems
self.tabBarController.tabBar.unselectedItemTintColor = Theme.current.tabbarUnselectedItemsColor

//

Or if the root is the tabController

let tab = UIApplication.shared.keyWindow?.rootViewController as! UITabBarController
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • Damn, I thought I can change it in a single file only. I certainly cannot set it as a root view controller in `AppDelegate` because it's not a `rootViewController` – Dani Aug 08 '18 at 12:30
  • 1
    anywhere you change the Theme if the tabBarController is presented access it and change the properties as **viewWillAppear** is called when there is another VC above the tabBar poped , it works after relaunch as viewWillAppear is called again for sure – Shehata Gamal Aug 08 '18 at 12:32