I have a UITabBarController subclass and I want to add a small white rectangular icon below the selected UITabBarItem icon. I used a UIView and I'm getting the TabBarItem as a subview and adding the view as a subview to it. I'm doing this in viewWillAppear, it shows but when I select another tab it doesn't appear under that tab bar item.
Here is my code:
let view = orderedTabBarItemViews()[selectedIndex]
bottomIcon.frame = CGRect(x: 0, y: 42, width: 10, height: 3)
bottomIcon.center = CGPoint(x: view.bounds.size.width / 2, y: view.bounds.size.height / 2)
bottomIcon.backgroundColor = UIColor.white
bottomIcon.layer.cornerRadius = 2
view.addSubview(bottomIcon)
The orderedTabBarItemViews() function gets the the TabBarItems as an array of UIViews.
Here is an Image of what I'm trying to achieve

This is a quick hack I created using unicode character ⬬:
extension UITabBarController {
func addDotToTabBarItemWith(index: Int,size: CGFloat,color: UIColor, verticalOffset: CGFloat = 1.0) {
// set distance from tab bar icons
for tabItem in self.viewControllers! {
tabItem.tabBarItem.titlePositionAdjustment = UIOffset(horizontal: 0.0, vertical: verticalOffset)
}
// set default appearance for tabbar icon title
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: color,NSFontAttributeName:UIFont(name: "American Typewriter", size: size)!], for: .normal)
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: color,NSFontAttributeName:UIFont(name: "American Typewriter", size: size)!], for: .selected)
// place the dot
guard let vc = self.viewControllers?[index] else {
log.error("Couldn't find a TabBar Controller with index:\(index)")
return
}
vc.tabBarItem.title = "⬬"
}
}
I don't think there is a handy way adding and showing/hiding a view.
I suggest you to do this using UIImages - so one with dot for selected state and another without dot for non-selected state.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With