Make Extension of UITabBarController
extension UITabBarController {
func setBadges(badgeValues: [Int]) {
for view in self.tabBar.subviews {
if view is CustomTabBadge {
view.removeFromSuperview()
}
}
for index in 0...badgeValues.count-1 {
if badgeValues[index] != 0 {
addBadge(index, value: badgeValues[index])
}
}
}
func addBadge(index: Int, value: Int) {
let badgeView = CustomTabBadge()
badgeView.clipsToBounds = true
badgeView.textColor = TheamColor
badgeView.textAlignment = .Center
badgeView.font = UIFont(name: fArticulatCFDemiBold, size: 11)!
badgeView.text = String(value)
badgeView.backgroundColor = UIColor.whiteColor()
badgeView.tag = index
badgeView.borderColor = TheamColor
badgeView.borderWidth = 1
tabBar.addSubview(badgeView)
self.positionBadges()
}
override public func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.positionBadges()
}
// Positioning
func positionBadges() {
var tabbarButtons = self.tabBar.subviews.filter { (view: UIView) -> Bool in
return view.userInteractionEnabled // only UITabBarButton are userInteractionEnabled
}
tabbarButtons = tabbarButtons.sort({ $0.frame.origin.x < $1.frame.origin.x })
for view in self.tabBar.subviews {
if view is CustomTabBadge {
let badgeView = view as! CustomTabBadge
self.positionBadge(badgeView, items:tabbarButtons, index: badgeView.tag)
}
}
}
func positionBadge(badgeView: UIView, items: [UIView], index: Int) {
let itemView = items[index]
let center = itemView.center
let xOffset: CGFloat = 10
let yOffset: CGFloat = -5
badgeView.frame.size = CGSizeMake(17, 17)
badgeView.center = CGPointMake(center.x + xOffset, center.y + yOffset)
badgeView.layer.cornerRadius = badgeView.bounds.width/2
tabBar.bringSubviewToFront(badgeView)
}
}
Use Simple Method like:
self.tabBarController.setBadges([0,0,0,0,Int(count)!]) or self.tabBarController.addBadge(4, value: 1)