以编程方式为每个链接设置 UITabBarItem 图标 ViewController

Programmatically set the UITabBarItem icon for every linked ViewController

目前我们正在像这样更改 UITabBarItem 中显示的图像:

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

问题在于,您必须单击每个选项卡才能加载相应的图像。 如果我获得所有 UITabBarItems 的列表,我想我可以更改 UITabBarViewController 中的图像。但是这个列表总是空的。

执行此操作的正确方法是什么?

我发现,如果我将此代码添加到 UITabBarController 中的 viewDidAppear,它将起作用。

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

另一种可能更 Swift-y 的方法是从选项卡字典中设置图标。我们有一个用于选项卡名称的枚举 TabTitles,以及用于查找它的 tabIcons

这样,如果您添加标签或更改顺序,就没有那么多需要记住更改的内容了。

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

对Swift使用item.image = UIImage.fontAwesomeIcon(name: glyph, textColor: UIColor.black, size: CGSize(width: 30, height: 30)) 3.

另外记得导入FontAwesome_swift

Swift 5

您可以通过第一个控制器 'viewDidLoad' 方法设置 tabBarItems 图标。

   func setupTabBar() {
    tabBarController?.tabBar.items![0].title = "Week"
    tabBarController?.tabBar.items![0].image = #imageLiteral(resourceName: "icons8-clinic")     
    tabBarController?.tabBar.items![1].title = "Profile"
    tabBarController?.tabBar.items![1].image = #imageLiteral(resourceName: "icons8-phone_not_being_used_filled")
}