Search code examples
iosswift3uinavigationbaralphauicolor

Setting a background color with alpha in Navigation bar


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?


Solution

  • 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