Reputation: 65
As the title implies I'm wondering if there is a way to change the background colour of a UINavigationBar in Swift. I know this question has been asked once before as I found this question here but I couldn't get any of the code to work when I tried to bring it up to date. I have linked the custom class which is a subclass of UINavigationController
. Currently, the background colour of all the child UINavigationItem
's have the default background colour of a slightly tinted white. I want to be able to change their colour to fit the rest of the UI elements in my app as most of them are extremely dark so I'm trying to change that below there is a picture of what I'm trying to replicate.
Is there is a more recent way to do this? Maybe using User defined runtime attributes. I'm out of ideas.
I've tried
@objc func changebarColor(){
self.navigationController?.navigationBar.barTintColor = UIColor.red;
}
override func viewDidLoad() {
super.viewDidLoad()
changebarColor()
}
And
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.barStyle = UIBarStyle.blackTranslucent
self.navigationController?.navigationBar.barTintColor = UIColor.red;
}
And
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController!.navigationBar .setBackgroundImage(UIImage(), for: UIBarMetrics.default)
self.navigationController!.navigationBar.shadowImage = UIImage();
self.navigationController!.navigationBar.isTranslucent = true;
self.navigationController!.navigationBar.backgroundColor = UIColor.red;
}
As well as all of the other answers posted on the page. Slightly tweaking them to remove errors.
Upvotes: 0
Views: 176
Reputation: 1837
You are on the right track, but you are calling it in the wrong place. You should move it to viewWillAppear
which is called every time you view is going to be displayed. viewDidLoad()
is only called once.
This means that another view controller or even the OS can change the colour of your navigation bar after viewDidLoad()
override func viewWillAppear(_ animated:Bool)
{
super.viewWillAppear( animated)
self.navigationController?.navigationBar.barTintColor = UIColor.red
}
Also, you don't need semi colons in Swift.
Upvotes: 3