如何更改选项卡栏控制器中每个选项卡的外观?

How do I change the appearance of every tab in the Tab Bar Controller?

override func viewDidLoad() {   
    super.viewDidLoad()
    tabBarItem.imageInsets = UIEdgeInsets(top: 5, left: 0, bottom: -5, right: 0)
}

我将它放在我的选项卡的视图控制器之一中。但是,这只会设置该特定视图。我将其复制并粘贴到所有其他控制器,但它仅在我点击它们时设置。 (如果我不点击它们,viewDidLoad 不会 运行。)

我希望所有选项卡在显示所有选项卡时立即显示此插入图像。

一个选项是遍历选项卡栏的所有控制器。将此代码放在 UITabBarController 初始化之后(及其 viewControllers 被填充),或者放在第一个视图控制器的 viewDidLoad 中(它只需要 运行 一次).

// Loop through ALL the controllers in the TabBarController and set their tab bar item imageInsets.
for (index, controller) in enumerate(tabBarController.viewControllers) {
    controller.tabBarItem.imageInsets = UIEdgeInsets(top: 5, left: 0, bottom: -5, right: 0)
}