Swift 2.2如何更改标签栏控制器的背景颜色 [英] Swift 2.2 How to change background color of tab bar controller

查看:81
本文介绍了Swift 2.2如何更改标签栏控制器的背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试更改标签栏的背景,并在ObjC中阅读了很多帖子,其中很多都很老。但我没有找到任何Swift,这就是我正在使用的。

I've been trying to change the background of the tab bar, and have read many posts here in ObjC, many of them quite old. But I didn't find any for Swift, which is what I'm using.

我终于想出了如何从代码中做到这一点,所以标签栏颜色可以随着每个主题颜色的变化而改变。以下是我使用的参考资料:

I finally figured out how to do it from code, so the tab bar colors can be changed with each theme color change. Here are the references that I used:

  override func viewWillAppear(animated: Bool) {
    // set tab bar background color, including the More tab
    self.tabBarController?.tabBar.backgroundColor = UIColor.blueColor()
  }

我将此代码放在视图控制器中,以便在应用启动时显示第一个选项卡,以便它首先运行。据我所知,即使我有8个标签并使用更多...标签,它也能正常工作。

I put this code in the view controller for the first tab that appears when the app starts up, so that it gets run "first." It works fine as far as I can tell, even when I have 8 tabs and use the More... tab.

我将相同的代码绑定到各种按钮标签,所以我可以在我的代码中的任何地方更改标签栏颜色。

And I bound the same code to buttons in various tabs, so I can change the tab bar color from anywhere in my code.

但我承认,作为一个新手,我不确定这是改变的最佳位置标签栏颜色。如果这是错误的地方,请更正我。

But I confess that as a newbie, I'm not sure that's the best location to change the tab bar color. If this is the wrong place, please correct me.

我在这里发布此代码,因为它可以节省我几个小时,我希望它可以拯救别人一些(快速)时间。

I post this code here since it would have saved me a few hours, and I hope that it can save someone else some (swift) time.

推荐答案

这是改变 UITabBar <的一种很好的方法/ code>。如果你想避免在嵌入 UITabBarController 内的每个viewController中设置颜色,你也可以创建一个 UITabBarController的子类并将其设置在那里。这种方式无论首先出现什么页面,都会设置颜色。

This is a fine way to change the color of a UITabBar. If you want to avoid setting the color in every viewController that is embedded inside of your UITabBarController, you could also create a subclass of UITabBarController and set it there. This way no matter what page comes up first, the color will be set.

创建的子类UITabBarController ,只需转到文件>新建>文件>可可触摸类...然后像在这张照片中设置您的文件

To create a subclass of UITabBarController, just go to file > new > file > cocoa touch class...Then setup your file like in this photo

现在在你的故事板中,在tabBarController上设置自定义类

Now in your storyboard, set the custom class on your tabBarController

最后,在你的文件中你创建了 MyTabBarController (或你称之为的任何东西):

Finally, in your file you created MyTabBarController (or whatever you called it):

class MyTabBarController: UITabBarController {

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    self.tabBar.barTintColor = .blueColor()
}
...

这篇关于Swift 2.2如何更改标签栏控制器的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆