Tag Archives: UITabBarController

How to set a badge value on a UITabBarController item

Screen Shot 2014-04-21 at 08.53.48

Each view controller has access to a UITabBarItem. This is only displayed if the current view controller is part of a UITabBarController. A UITabBarItem has a badge value which is that little red mark above icon and name to the tab bar item itself (as shown in the screenshot above: LIVE is currently the badgeValue of the tab bar item).

Here’s how you can set the badge value:

This approach will work if you have direct access to the class in the view controller. More commonly though you’ll have your own class embedded in a UINavigationController, in which case its tab bar item (and title) is shown on that tab.

In which case you can access the tab bar item like this:

How to create a UITabBarController in code

Tab Bar Controllers are setup with an array of view controllers. We’ll create those first, then we simply give said array to our tab bar controller.

In this example, this is a subclass of UITabBarController:

Note that I’m also setting the title property of each view controller. This is displayed as the tab bar text and is left blank if not specified. To override this behaviour and/or specify graphics, set the UITabBarItem of each individual view controller.

The method that creates the view controllers is very straightforward: in this example I have a single ViewController in my storyboard (with a Storyboard ID of “PlainViewController”). All we do here is specify a funky background colour to tell them apart:

Note that the tab bar configuration is not set in stone: you can switch out the view controllers on the fly by calling the setViewcontrollers method again, passing in new content.

Here’s a full working demo project that show it all in action:

and the class reference:

How to share data between Navigation Controllers

The Root Navigation Controller can serve as a data model. Each View Controller connected to the Navigation Controller via push segue can access its properties like so:

Here’s an example. MyNavController is the class for the Navigation Controller. This snipped is called from any View Controller in sequence and assumes we have an integer myNumber which is increased by one:

The same principle works for Tab Bar Controllers too.