Last active
February 3, 2016 10:18
-
-
Save vienvu89/9de71548b2abc0e7ab43 to your computer and use it in GitHub Desktop.
Set Background for Tabbar Item Active and change color certain item:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Add background color to middle tabBarItem | |
let itemIndex = 2 | |
let bgColor = UIColor(red: 0.08, green: 0.726, blue: 0.702, alpha: 1.0) | |
let itemWidth = tabBar.frame.width / CGFloat(tabBar.items!.count) | |
let bgView = UIView(frame: CGRectMake(itemWidth * itemIndex, 0, itemWidth, tabBar.frame.height)) | |
bgView.backgroundColor = bgColor | |
tabBar.insertSubview(bgView, atIndex: 0) | |
// set red as selected background color | |
let numberOfItems = CGFloat(tabBar.items!.count) | |
let tabBarItemSize = CGSize(width: tabBar.frame.width / numberOfItems, height: tabBar.frame.height) | |
tabBar.selectionIndicatorImage = UIImage.imageWithColor(UIColor.redColor(), size: tabBarItemSize).resizableImageWithCapInsets(UIEdgeInsetsZero) | |
// remove default border | |
tabBar.frame.size.width = self.view.frame.width + 4 | |
extension UIImage { | |
class func imageWithColor(color: UIColor, size: CGSize) -> UIImage { | |
let rect: CGRect = CGRectMake(0, 0, size.width, size.height) | |
UIGraphicsBeginImageContextWithOptions(size, false, 0) | |
color.setFill() | |
UIRectFill(rect) | |
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext() | |
UIGraphicsEndImageContext() | |
return image | |
} | |
} | |
tabBar.frame.origin.x = -2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment