swiftuitabbaruiappearance

UINavigationBar.appearance().tintColor does not work in Swift


I ported a file from Objective_c to Swift that among its configurations changed the tabbar color: the code I used in objective-c was:

UIColor* barColor=[UIColor colorWithRed:.88 green:.05 blue:.05 alpha:1];
if([self.navigationController.navigationBar respondsToSelector:@selector(barTintColor)])
{
    // iOS7
    self.navigationController.navigationBar.barTintColor = barColor;
}
else
{
    [[UINavigationBar appearance] setTintColor:barColor];
    // older
    //self.navigationController.navigationBar.tintColor = barColor;
}
[super viewWillAppear:animated];

and the corresponding code in Swift is:

let barColor = UIColor(red:0.88, green:0.05, blue:0.05, alpha:1)
if UIDevice.currentDevice().systemVersion.compare("8.0", options: .NumericSearch) == .OrderedDescending
    {
        // iOS8+
     UINavigationBar.appearance().tintColor=barColor
     //UINavigationBar.appearance().translucent=false
    }
    else
    {
        self.navigationController!.navigationBar.barTintColor = barColor;
    }

Yet, while the objective-c code did change the tab-bar color, the corresponding swift code leave it unscathed, at least on the simulator. What I did wrong?


Solution

  • The issue was due to the navigationBar not being initialized at ViewWillAppear time possibly for a IOS 9 bug. I solved the issue by optionally accessing it as in:

    self.navigationController?.navigationBar.barTintColor = barColor;
    

    This code is fine from iOS7+ and so no condition is needed.