Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add small icon below selected UITabBarItem icon in Swift

Tags:

ios

uikit

swift

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

like image 225
Oluwatobi Omotayo Avatar asked Oct 31 '25 11:10

Oluwatobi Omotayo


2 Answers

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 = "⬬"
    }
}
like image 193
Claus Avatar answered Nov 03 '25 04:11

Claus


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.

like image 20
christian Avatar answered Nov 03 '25 04:11

christian