在每个视图控制器 [Swift] 中自定义 UITabBar.appearance

Customising the UITabBar.appearance in each View Controller [Swift]

我正在尝试将选项卡栏设置为在每个视图控制器上具有不同的背景图像。

class CharacterVC: UIViewController {

var tabBarApparence = UITabBar.appearance()

override func viewDidLoad() {
    super.viewDidLoad()

    tabBarApparence.backgroundImage = UIImage(named: "BlueTB") //Loaded from Image Asset
}

这很好用,并在该视图中将其更改为蓝色,但是当我转到下一个视图时,它保持蓝色并且不会更改为我使用以下代码编程的红色:

class AnonVC: UIViewController {

var tabBarApparence = UITabBar.appearance()

override func viewDidLoad() {
    super.viewDidLoad()
    tabBarApparence.backgroundImage = UIImage(named: "RedTabBar")
    // addtional code here
}

我还有另外 2 个视图控制器,一个应该显示图像的绿色版本,另一个显示图像的紫色版本。

有什么建议可以解决这个问题吗?

  1. 将代码替换为 viewWillAppear()
  2. 最好将 backgroundImage 设置为 tabBar,而不是 UITabBar.appearance()

如果你想在视图控制器中改变 TabBar 的外观是很容易的。您可以在函数 viewDidLoad 或 viewWillAppear 中执行此操作。代码是下一个:

// Set color of titles and icons in tabBar
self.tabBarController?.tabBar.tintColor = UIColor.redColor()
// Set color of background tabBar
self.tabBarController?.tabBar.barTintColor = UIColor.blueColor()