I would like a different background color when the user selects a tab bar item than when it is unselected.
Follow this Steps:
Create SubClass of UITabBarController
Go to viewDidAppear
of UITabBarController
subclass
Now Find the size of TabBarItem,
UITabBar *tabBar = self.tabBar;
CGSize imgSize = CGSizeMake(tabBar.frame.size.width/tabBar.items.count,tabBar.frame.size.height);
Now Create the image with that size,
//Create Image
UIGraphicsBeginImageContextWithOptions(imgSize, NO, 0);
UIBezierPath* p =
[UIBezierPath bezierPathWithRect:CGRectMake(0,0,imgSize.width,imgSize.height)];
[[UIColor blueColor] setFill];
[p fill];
UIImage* finalImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Now, Assign this image to TabBar's SelectionIndicatorImage
[tabBar setSelectionIndicatorImage:finalImg];
Swift 4 Version:
let imgSize = CGSize(width: tabBar.frame.size.width / CGFloat(tabBar.items!.count),
height: tabBar.frame.size.height)
UIGraphicsBeginImageContextWithOptions(imgSize, false, 0)
let p = UIBezierPath(rect: CGRect(x: 0, y: 0, width: imgSize.width,
height: imgSize.height))
UIColor.blue.setFill()
p.fill()
let finalImg = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UITabBar.appearance().selectionIndicatorImage = finalImg