将UI导航栏设置为在Swift xCode中部分半透明

我想使我的导航栏有一个颜色的色调,但不能完全半透明。 这里是我有的代码和他们的结果:

UINavigationBar.appearance().setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default) UINavigationBar.appearance().shadowImage = UIImage() UINavigationBar.appearance().translucent = true UINavigationBar.appearance().barTintColor = UIColor(red: 0, green: 107/255, blue: 178/255, alpha: 0.5) 

全是半透明的

但是,如果我把“半透明”变成假,即使用这个代码:

  UINavigationBar.appearance().setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default) UINavigationBar.appearance().shadowImage = UIImage() UINavigationBar.appearance().translucent = false UINavigationBar.appearance().barTintColor = UIColor(red: 0, green: 107/255, blue: 178/255, alpha: 0.5) 

我得到这个结果: 第二个结果

如何让酒吧的alpha值为0.5或“部分半透明”?

谢谢,任何帮助将不胜感激。

我会为导航栏设置一个半透明的背景图像。

使用此代码:

 UINavigationBar.appearance().setBackgroundImage(UIColor.green.toImage()?.imageWithAlpha(alpha: 0.5), for: .default) 

使用了两个扩展:

从UIColor创build一个UIImage:

 extension UIColor { func toImage() -> UIImage? { return toImageWithSize(size: CGSize(width: 1, height: 1)) } func toImageWithSize(size: CGSize) -> UIImage? { UIGraphicsBeginImageContext(size) if let ctx = UIGraphicsGetCurrentContext() { let rectangle = CGRect(x: 0, y: 0, width: size.width, height: size.height) ctx.setFillColor(self.cgColor) ctx.addRect(rectangle) ctx.drawPath(using: .fill) let colorImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return colorImage } else { return nil } } } 

使用指定的Alpha从UIImage创build一个新的UIImage:

 extension UIImage { func imageWithAlpha(alpha: CGFloat) -> UIImage? { UIGraphicsBeginImageContextWithOptions(size, false, scale) draw(at: CGPoint.zero, blendMode: .normal, alpha: alpha) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } }