I would like a different background color when the user selects a tab bar item than when it is unselected.
My answer is similar to @Mehul Thakkar but it is in Swift 4 and to improve on his answer I would say that if you place the code in viewDidAppear
as he suggests users will see the change happening which is not good user experience.
So create the custom class for your tabbar controller and in viewDidLoad
place the following code:
let singleTabWidth: CGFloat = self.tabBar.frame.size.width / CGFloat((self.tabBar.items?.count)!)
let singleTabSize = CGSize(width:singleTabWidth , height: self.tabBar.frame.size.height)
let selectedTabBackgroundImage: UIImage = self.imageWithColor(color: .white, size: singleTabSize)
self.tabBar.selectionIndicatorImage = selectedTabBackgroundImage
The imageWithColor
function is below for you:
//image with color and size
func imageWithColor(color: UIColor, size: CGSize) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context!.setFillColor(color.cgColor)
context!.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
Hope this helps someone.