Sujal
Sujal

Reputation: 1507

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.

enter image description here

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.

P.S. The navigation bar has to stay translucent.

Upvotes: 3

Views: 1515

Answers (3)

Wes Chua
Wes Chua

Reputation: 1076

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
    

Upvotes: 0

Hitesh Surani
Hitesh Surani

Reputation: 13537

You just need to set opacity of headerView to 0.85

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

Output

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.

Upvotes: 1

BhargavR
BhargavR

Reputation: 1133

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

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

Hope this helps.

Upvotes: 0

Related Questions