Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Tab Bar background transparency

I am trying to make my Tab Bar in my tab bar controller to have a low opacity background, so it is semi transparent, i am trying to do this programatically, however the background changes to the correct color, but always appears solid, with no transparency.

Here is the code in my TabBarViewController

class TabBarViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tabBar.unselectedItemTintColor = UIColor(red: 17.0/255.0, green: 70.0/255.0, blue: 95.0/255.0, alpha: 0.4)
        self.tabBar.barTintColor = UIColor(red: 17.0/255.0, green: 70.0/255.0, blue: 95.0/255.0, alpha: 0.5)


        // Do any additional setup after loading the view.
    }
}
like image 538
Al Hennessey Avatar asked Aug 22 '17 20:08

Al Hennessey


2 Answers

For such a case, you should generate a customized UIImage to the tab bar backgroundimage property.

Let's assume that your desired color for your tab bar -that should be transparent- is black, you could implement in your custom UITabBarController:

class TabBarViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let transperentBlackColor = UIColor(displayP3Red: 0, green: 0, blue: 0, alpha: 0.5)

        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
        transperentBlackColor.setFill()
        UIRectFill(rect)

        if let image = UIGraphicsGetImageFromCurrentImageContext() {
            tabBar.backgroundImage = image
        }

        UIGraphicsEndImageContext()
    }
}

So, as an Output, if we assumed that the background color of your view controller is blue, it should looks like:

enter image description here

As shown, the tab bar is not purely black, it contains transparency (0.5) as expected.

Also, for checking how you could generate a solid-color UIImage, you could check this SO answer : Create UIImage with solid color in Swift.

like image 76
Ahmad F Avatar answered Oct 22 '22 17:10

Ahmad F


Just replace barTintColor with backgroundColor.

override func viewDidLoad() {
     super.viewDidLoad()
     self.tabBar.unselectedItemTintColor = UIColor(red: 17.0/255.0, green: 70.0/255.0, blue: 95.0/255.0, alpha: 0.4)
     self.tabBar.backgroundColor = UIColor(red: 17.0/255.0, green: 70.0/255.0, blue: 95.0/255.0, alpha: 0.5)
        // Do any additional setup after loading the view.
}

enter image description here

like image 1
PGLongo Avatar answered Oct 22 '22 15:10

PGLongo