简体   繁体   中英

How to set a view's color to match a translucent navigation bar's color?

I need to increase the height of the navigation bar. For this, I have added a view (of desired height) under the navigation bar. The navigation bar is set to be translucent . So the nav bar color is rendered slightly different than the actual hex value. Now I need to match the navigation bar's color to the view below. Following is the code that I am using.

func setupNavigationBar() {
    title = "Profile"

    self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: ""), for: .default)
    self.navigationController?.navigationBar.shadowImage = UIImage(named: "")

    headerView.backgroundColor = navigationController?.navigationBar.barTintColor
    headerView.isOpaque = false  
}

I am getting different shades as below.

在此处输入图片说明

How can i make the view's color to be the same as navigation bar's color? I can get near to the desired color by reducing the view's alpha but I am doubtful about that approach since there is no standard defined regarding it.

PS The navigation bar has to stay translucent.

Set the background colour to clear for the navigation bar using :

self.navigationController?.navigationBar.backgroundColor = UIColor.clear

Hope this helps.

You just need to set opacity of headerView to 0.85

headerView.backgroundColor = navigationController?.navigationBar.barTintColor
headerView.layer.opacity = 0.85
headerView.isOpaque = false

输出量

You can download the sample code from here :

Please ignore other unused code in the sample code.

Explanation:

When you're set navigationController style as translucent then the system automatically take layer opacity 0.85 for UINavigationController

I personally check it by iterating all subview of UINavigationController .

You can set the background color to nil and it will follow the background color.

let appearance = UINavigationBarAppearance() 
appearance.configureWithOpaqueBackground() 
appearance.backgroundColor = nil

navigationController?.navigationBar.standardAppearance = 
appearance 

navigationController?.navigationBar.compactAppearance = appearance
    

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