Setting UI Navigation Bar to part translucent in Swift xCode

时光毁灭记忆、已成空白 提交于 2019-12-21 20:13:32

问题


I want to make my navigation bar have a tinge of a colour but not go completely translucent. Here is the code I have and their 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)

But if I turn the 'translucent' to false i.e 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:

How do I make the bar have an alpha value of 0.5 or be 'part translucent'?

Thank you, any help will be appreciated.


回答1:


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 an 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 an UIImage with a 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
    }
}


来源:https://stackoverflow.com/questions/31506381/setting-ui-navigation-bar-to-part-translucent-in-swift-xcode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!