Fate Riddle Fate Riddle - 4 months ago 18
Swift Question

Code in ViewWillAppear doesn't work, why?

my app start with a tab bar controller, then every tab goes with a navigation VC. I wish to hide tab bar in the bottom whenever I start to navigate into a second VC, and also change the color of navigation bar to orange color, here's the code in the 2nd VC:

override func viewWillAppear(animated: Bool) {
var tabBarHide = self.tabBarController!.tabBar.hidden
print(tabBarHide)
if !tabBarHide {
tabBarHide = true
}
print(tabBarHide)
UINavigationBar.appearance().barTintColor = UIColor.init(red: 247/255, green: 119/255, blue: 0/255, alpha: 1)

}


It does print out: false & true every time I navigate to this VC, but nothing happened to the view. It doesn't work. Why?

Answer

You can't use the UIAppearance proxy to alter the appearance of an object that is already in the view hierarchy. From the UIAppearance documentation:

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.

You can modify the tint color of the active navigation bar directly:

self.navigationController?.navigationBar.tintColor = UIColor.init(red: 247/255, green: 119/255, blue: 0/255, alpha: 1)

As for why your tab bar isn't hiding, you are modifying your local variable, not the hidden property of the tab bar. You want:

self.tabBarController?.tabBar.hidden = true

So your viewWillAppear should be something like:

override func viewWillAppear(animated: Bool) {

    super.viewWillAppear(animated)

    self.tabBarController?.tabBar.hidden = true
    self.navigationController?.navigationBar.tintColor = UIColor.init(red: 247/255, green: 119/255, blue: 0/255, alpha: 1)

}