Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically set the UITabBarItem icon for every linked ViewController

Currently we are changing the image shown in the UITabBarItem like this:

override func viewDidLoad() {
    super.viewDidLoad()

    // register additional NIB files
    tableView.registerNib(UINib(nibName: "WeekDayTableViewCell", bundle: nil), forCellReuseIdentifier: "WeekDayCell")

    tabBarItem.title = "Week".localized
    tabBarItem.image = UIImage.fontAwesomeIconWithName(FontAwesome.Calendar, textColor: UIColor.blueColor(), size: CGSizeMake(30, 30))
}

The problem with this is, that you have to click on every tab to load the corresponding images. I thought I could change the images in the UITabBarViewController if I get the list of all UITabBarItems. But this list is always empty.

Which is the correct way to do this?

like image 424
Pascal Avatar asked May 12 '26 18:05

Pascal


2 Answers

An alternative—perhaps a more Swift-y—way to do this is to set the icons from a Dictionary of tabs. We have an enum TabTitles for the names of the tabs, and tabIcons to look it up.

This way, there's not so much to remember to change if you add a tab or change the order.

private enum TabTitles: String, CustomStringConvertible {
    case Stacks
    case Settings
    case Clusters
    case Services
    case Registries

    private var description: String {
        return self.rawValue
    }
}

private var tabIcons = [
    TabTitles.Stacks: FontAwesome.Clone,
    TabTitles.Settings: FontAwesome.Gears,
    TabTitles.Clusters: FontAwesome.Cubes,
    TabTitles.Services: FontAwesome.Exchange,
    TabTitles.Registries: FontAwesome.Institution
]

override func viewDidLoad() {
    super.viewDidLoad()

    if let tabBarItems = tabBar.items {
        for item in tabBarItems {
            if let title = item.title,
              tab = TabTitles(rawValue: title),
              glyph = tabIcons[tab] {
                item.image = UIImage.fontAwesomeIconWithName(glyph, textColor: UIColor.blueColor(), size: CGSizeMake(30, 30))
            }
        }
    }
}
like image 92
Stephen Harrison Avatar answered May 14 '26 09:05

Stephen Harrison


I found out, if I add this code to the viewDidAppear in the UITabBarController it will work.

let tabBarItems = tabBar.items! as [UITabBarItem]

tabBarItems[0].title = "Week".localized
tabBarItems[0].image = UIImage.fontAwesomeIconWithName(FontAwesome.Calendar, textColor: UIColor.blueColor(), size: CGSizeMake(30, 30))

tabBarItems[1].title = "Settings".localized
tabBarItems[1].image = UIImage.fontAwesomeIconWithName(FontAwesome.Gears, textColor: UIColor.blueColor(), size: CGSizeMake(30, 30))
like image 20
Pascal Avatar answered May 14 '26 09:05

Pascal