2
votes

I'd like the background of a navigation bar to be a color with 0.5 alpha to be able to partially see the contents of the view below. I've tried to do like this:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    self.navigationController?.navigationBar.barTintColor = UIColor.blue
    self.navigationController?.navigationBar.isTranslucent = true
}

If I set isTranslucent to true, then the navigationBar color is clear. If I set isTranslucent to false, the color is opaque even if I set UIColor.blue.alpha(0.5)

How could I do this?

2

2 Answers

3
votes

If you just want the NavigationBar (excluding status bar) background with alpha.. Try this

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
    self.navigationController?.navigationBar.isTranslucent = true
    self.navigationController?.navigationBar.backgroundColor = UIColor.blue.withAlphaComponent(0.5)
}

If you want background color with alpha including status bar, Im afraid you have to use an image with alpha value. see this

0
votes

You can also make a image of the desired colour and transparency and then in your AppDelegate in the didFinishLaunchingWithOptions function simply add this:

//navigation bar
        let navBackgroundImage:UIImage! = UIImage(named: "nav.png")
        UINavigationBar.appearance().setBackgroundImage(navBackgroundImage, for: .default)

where nav.png is your image.

Hope this helps. :)