Configuring the user interface navigation bar for partial tinting in Swift xCode

I want my navigation bar to have a color cast, but not completely transparent. Here is the code I have and its results:

        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)

all translucent

But if I return 'translucent' to false, then use this code:

        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)

I get this result: second result

How to make the panel have an alpha value of 0.5 or be "translucent"?

Thanks, any help would be appreciated.

+4
source share
1 answer

I would set a translucent background image for the navigation bar.

Use this code:

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

Two extensions used:

Create a UIImage from UIColor:

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
                }
            }   
        }

Create a new UIImage from UIImage with the specified Alpha:

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
    }
}
0
source

Source: https://habr.com/ru/post/1598626/


All Articles