简体   繁体   中英

Is there a way to change the background colour of a UINavigationBar in swift 4

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM