Victor Krusenstråhle Victor Krusenstråhle - 3 months ago 23
Swift Question

Transparent navbar swift iOS


  1. This is what the project currently looks like

  2. And this is the code that I use

    func styleNavBar() {
    let navigationBarAppearace = UINavigationBar.appearance()
    navigationBarAppearace.tintColor = UIColor(red:1.0, green:1.0, blue:1.0, alpha:1.0)
    navigationBarAppearace.titleTextAttributes = [NSForegroundColorAttributeName:UIColor(red:1.00, green:1.00, blue:1.00, alpha:1.0)]
    navigationBarAppearace.translucent = true

    navigationBarAppearace.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.3)
    navigationBarAppearace.setBackgroundImage(UIImage(), forBarMetrics: .Default)}



I have tried to remove the following code, but then it looks like this.

navigationBarAppearace.setBackgroundImage(UIImage(), forBarMetrics: .Default)


My question is, how do I get the
navbar
to fill up to the top? and still have the same look

Answer

First, create an extension for UIImage which create image with solid color of specified size. Keep this extension in any ViewController at class label

extension UIImage {

    class func imageWithColor(color: UIColor, size: CGSize) -> UIImage {
        let rect: CGRect = CGRectMake(0, 0, size.width, size.height)
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        color.setFill()
        UIRectFill(rect)
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

then use the below method to customise your navbar

func styleNavBar() {
        let navigationBarAppearace = UINavigationBar.appearance()
        navigationBarAppearace.tintColor = UIColor(red:1.0, green:1.0, blue:1.0, alpha:1.0)
        navigationBarAppearace.titleTextAttributes = [NSForegroundColorAttributeName:UIColor(red:1.00, green:1.00, blue:1.00, alpha:1.0)]
        navigationBarAppearace.translucent = true

        let colorImage = UIImage.imageWithColor(UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.3), size: CGSizeMake(UIScreen.mainScreen().bounds.width, 64))
        navigationBarAppearace.setBackgroundImage(colorImage, forBarMetrics: .Default)
    }

Hope this will solve your problem.

Comments