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?
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))
}
}
}
}
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))
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