简体   繁体   中英

Refresh Navigation Bar background color

I have a navigation bar with the same color as the view's background. If the user presses a button, the color of the view is changing, but the color of the nav bar isn't. If I'm trying to change it manually, with

self.navigationController?.navigationBar.barTintColor = UIColor(red: 104.0/255.0, green: 154.0/255.0, blue: 26.0/255.0, alpha: 1.0)

It does changes the navbar background color, but it's not exactly the same as the view's color, even I set the same values for the background.

How can I set the nav bar's color to be the same as the view's color?

There are 2 ways:

1) Set navigation bar as non-translucent:

navigationController?.navigationBar.barTintColor = UIColor(red: 1.0, green: 0, blue: 0, alpha: 1.0)
navigationController?.navigationBar.isTranslucent = false

2) Set background image for navigation bar:

navigationController?.navigationBar.setBackgroundImage(UIImage(named: "red"), for: .default)

You can also provide a generated UIImage based on UIColor with a function like this:

func convertUIColorToUIImage(_ color: UIColor, size: CGSize) -> UIImage {
    let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
    UIGraphicsBeginImageContextWithOptions(size, false, 0)
    color.setFill()
    UIRectFill(rect)
    let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return image
}

The difference between your navigation bar and in ViewController is because the navigation bar is translucent, the system will apply a default alpha value for the navigation bar.

self.navigationController?.navigationBar.isTranslucent = false
self.navigationController?.navigationBar.barTintColor = UIColor(red: 104.0/255.0, green: 154.0/255.0, blue: 26.0/255.0, alpha: 1.0)

Or Manually :

Difference in navigation bar and ViewController background colour is 20. which gives UINavigationBar it's built-in styling by giving this a "glossy" look.

So R=104 | G=154 | B=26 will become R=84 | G=134 B| B=6.

navigationController?.navigationBar.barTintColor = UIColor(red: 84.0/255.0, green: 134.0/255.0, blue: 6.0/255.0, alpha: 1.0)
self.view.backgroundColor = UIColor(red: 104.0/255.0, green: 154.0/255.0, blue: 26.0/255.0, alpha: 26.0)

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