Oluwatobi Omotayo
Oluwatobi Omotayo

Reputation: 1879

How to add small icon below selected UITabBarItem icon in 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

Upvotes: 4

Views: 1775

Answers (3)

Claus
Claus

Reputation: 5742

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 = "⬬"
    }
}

Upvotes: 2

Sulthan
Sulthan

Reputation: 130152

There are several options:

  1. Add it as a part of the selected image. That's the most simple solution.

  2. Add it as a tab label (e.g. using - character, or some better unicode character, e.g. or ) with a large font.

  3. Add it as an overlay to UITabBar.

Upvotes: 1

christian
christian

Reputation: 495

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.

Upvotes: 1

Related Questions