Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reloading tab bar appearance

Tags:

ios

swift

tabbar

I am trying to reload the tab bar after the user changes the appearance of the app from light to dark mode and vice versa. I am able to update everything in the app except the tab bar. I don't want to force the user to close the app.

like image 275
Omr Avatar asked Jul 13 '18 17:07

Omr


2 Answers

If you try to look at docs about UIAppearance, you'll see the note:

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.

Based on this note you can change appearance with a little trick by remove and immediately set back the most top view in the hierarchy after applying changes to appearance:

guard let currentView = (UIApplication.shared.delegate as? AppDelegate)?.window?.rootViewController?.view,
    let superview = currentView.superview else { return }

UITabBar.appearance().tintColor = .green

currentView.removeFromSuperview()
superview.addSubview(currentView)
like image 163
pacification Avatar answered Oct 13 '22 01:10

pacification


With iOS 13 you can override traitCollectionDidChange(_:) in UITabBarController to make changes. See documentation.

Example:

class TabBarControllerViewController: UITabBarController {

    ...

    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        self.tabBar.barTintColor = UIColor.red
        self.tabBar.unselectedItemTintColor = UIColor.darkGray
        self.tabBar.tintColor = UIColor.white
  }
}
like image 28
jlagrone Avatar answered Oct 13 '22 00:10

jlagrone