简体   繁体   English

如何设置视图的颜色以匹配半透明导航栏的颜色?

[英]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.我可以通过减少视图的 alpha 来接近所需的颜色,但我对这种方法表示怀疑,因为没有关于它的标准定义。

PS The navigation bar has to stay translucent. PS 导航栏必须保持半透明。

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 opacity设置为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 当您将navigationController样式设置为translucent ,系统会自动为UINavigationController图层不透明度0.85

I personally check it by iterating all subview of UINavigationController . 我亲自通过iterating UINavigationController所有子视图进行检查。

You can set the background color to nil and it will follow the background color.您可以将背景颜色设置为 nil,它将跟随背景颜色。

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

navigationController?.navigationBar.standardAppearance = 
appearance 

navigationController?.navigationBar.compactAppearance = appearance
    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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