繁体   English   中英

更改标签栏项目图像和文本颜色 iOS

[英]Changing tab bar item image and text color iOS

这是我的标签栏:

在此处输入图像描述

下图显示了正在运行的程序和选中的“NEWS”项:

在此处输入图像描述

很明显,条形色调颜色可以正常工作,如我所愿!

但 tintColor 只影响图像而不影响文本。

Also, when the an item is selected (as seen above, news) the item color goes blue? 我该如何防止这种情况发生。 我希望它保持白色。

为什么文本在选中时变为白色,而在取消选中时却没有?

我基本上希望项目颜色和文本颜色始终为白色。

我如何实现这一目标? 谢谢你的帮助。

每件商品是否都需要 swift 代码?

编辑:

在此处输入图像描述

来自 UITabBarItem 类文档:

默认情况下,实际未选择和已选择的图像是根据源图像中的 alpha 值自动创建的。 为防止系统着色,请使用 UIImageRenderingModeAlwaysOriginal 提供图像。

线索不在于你是否使用 UIImageRenderingModeAlwaysOriginal,重要的是何时使用它。

为了防止未选中项目的灰色,您只需要防止未选中图像的系统着色。 以下是如何执行此操作:

var firstViewController:UIViewController = UIViewController()
// The following statement is what you need
var customTabBarItem:UITabBarItem = UITabBarItem(title: nil, image: UIImage(named: "YOUR_IMAGE_NAME")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal), selectedImage: UIImage(named: "YOUR_IMAGE_NAME"))
firstViewController.tabBarItem = customTabBarItem

如您所见,我要求 iOS 仅将图像的原始颜色(白色、黄色、红色等)应用于 UNSELECTED 状态,而将图像保留为 SELECTED 状态。

此外,您可能需要为选项卡栏添加色调,以便为 SELECTED 状态应用不同的颜色(而不是默认的 iOS 蓝色)。 根据上面的屏幕截图,您正在为所选状态应用白色:

self.tabBar.tintColor = UIColor.whiteColor()

编辑:

在此处输入图片说明

斯威夫特 3

我通过创建一个自定义标签栏控制器并将此代码添加到viewDidLoad方法中来做到这一点。

    if let count = self.tabBar.items?.count {
        for i in 0...(count-1) {
            let imageNameForSelectedState   = arrayOfImageNameForSelectedState[i]
            let imageNameForUnselectedState = arrayOfImageNameForUnselectedState[i]

            self.tabBar.items?[i].selectedImage = UIImage(named: imageNameForSelectedState)?.withRenderingMode(.alwaysOriginal)
            self.tabBar.items?[i].image = UIImage(named: imageNameForUnselectedState)?.withRenderingMode(.alwaysOriginal)
        }
    }

    let selectedColor   = UIColor(red: 246.0/255.0, green: 155.0/255.0, blue: 13.0/255.0, alpha: 1.0)
    let unselectedColor = UIColor(red: 16.0/255.0, green: 224.0/255.0, blue: 223.0/255.0, alpha: 1.0)

    UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: unselectedColor], for: .normal)
    UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: selectedColor], for: .selected)

它对我有用!

在此处输入图片说明

迅速


对于图像:

custom.tabBarItem = UITabBarItem(title: "Home", image: UIImage(named: "tab_icon_normal"), selectedImage: UIImage(named: "tab_icon_selected"))

对于文本:

UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.gray], for: .normal)
    
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.red], for: .selected)

Swift 4.2 和 Xcode 10

对我有用的解决方案:

  1. 图像设置- 从情节提要中设置 Bar Item Image 和 Selected Image。 要移除图像上的色调叠加,请转到资产目录,选择图像并更改其渲染模式,如下所示:

图像渲染模式

这将阻止标签栏组件设置其默认图像色调。

  1. 文本- 在这里我创建了一个简单的 UITabBarController 子类,并在它的 viewDidLoad 方法中自定义了默认和选定的文本颜色,如下所示:

     class HomeTabBarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() let appearance = UITabBarItem.appearance(whenContainedInInstancesOf: [HomeTabBarController.self]) appearance.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: .black], for: .normal) appearance.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: .red], for: .selected) } }

只需在 IB 的身份检查器中将此类设置为您的 Tab bar 控制器自定义类。

瞧! 就是这样。

iOS 13 更新

将此添加到您的 iOS 13 设置中:

if #available(iOS 13, *) {
    let appearance = UITabBarAppearance()
    appearance.stackedLayoutAppearance.selected.titleTextAttributes = [NSAttributedString.Key.foregroundColor: .red]
    tabBar.standardAppearance = appearance
}

Swift 4:在您的 UITabBarController 中通过此代码更改它

tabBar.unselectedItemTintColor = .black

斯威夫特 3

这对我有用(指的是设置 tabBarItems 图像颜色):

UITabBar.appearance().tintColor = ThemeColor.Blue

if let items = tabBarController.tabBar.items {
        let tabBarImages = getTabBarImages() // tabBarImages: [UIImage]
        for i in 0..<items.count {
            let tabBarItem = items[i]
            let tabBarImage = tabBarImages[i]
            tabBarItem.image = tabBarImage.withRenderingMode(.alwaysOriginal)
            tabBarItem.selectedImage = tabBarImage
        }
    }

我注意到,如果您使用渲染模式 = .alwaysOriginal 设置图像,则 UITabBar.tintColor 没有任何效果。

斯威夫特 3

首先,确保您已将 BOOLEAN 键“View controller-based status bar appearance”添加到 Info.plist,并将值设置为“NO”。

Appdelegate.swift

在“launchOptions:[UIApplicationLaunchOptionsKey: Any]?) -> Bool {”之后的某处插入代码

  1. 使用 RGB 颜色值更改标签栏本身的颜色:

UITabBar.appearance().barTintColor = UIColor(red: 0.145, green: 0.592, blue: 0.804, alpha: 1.00)

或默认 UI 颜色之一:

UITabBar.appearance().barTintColor = UIColor.white)


  1. 更改选项卡项的文本颜色:

所选项目

UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.white], for: .selected)

非活动项目

UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.black], for: .normal)

  1. 要更改图像的颜色,我认为最简单的方法是制作单独的图像,每个状态一个。

如果您不是从头开始制作图标,那么在 Photoshop 中制作交替的黑白版本相对容易。


Adobe Photoshop(几乎任何版本都可以)

确保您的图标图像具有透明背景,并且图标本身是纯黑色(或关闭)。

打开图像文件,将其保存在不同的文件名下(例如 exampleFilename-Inverted.png)

在“图像”菜单上的“调整”子菜单中:

点击“反转”

您现在拥有原始图标的底片。

在 XCode 中,在情节提要的 Tab Bar Properties 下将其中一张图像设置为“Selected Image”,并在“Bar Item”图像下指定“inactive”版本。

达达🍺

我知道这里有很多答案,但我找不到Swift 4.2/Swift 5.1的简单有效的复制/粘贴答案

tabBarController?.tabBar.tintColor = UIColor.red
tabBarController?.tabBar.unselectedItemTintColor = UIColor.green

或者像这样使用UITabBar.appearances()而不是tabBarController?.tabBar

UITabBar.appearances().tintColor = UIColor.red
UITabBar.appearances().unselectedItemTintColor = UIColor.green

图像必须是UIImageRenderingModeAlwaysTemplate

尝试将其添加到AppDelegate.swift (在应用程序方法中):

UITabBar.appearance().tintColor = UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 1.0)

// For WHITE color: 
UITabBar.appearance().tintColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0)

例子:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Tab bar icon selected color
    UITabBar.appearance().tintColor = UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 1.0)
    // For WHITE color: UITabBar.appearance().tintColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0)
    return true
}

例子:

在此处输入图片说明

在此处输入图片说明

我的英语太差了! 抱歉! :-)

斯威夫特 3.0

我创建了标签栏类文件并编写了以下代码

viewDidLoad

self.tabBar.barTintColor = UIColor.white
self.tabBar.isTranslucent = true

let selectedColor   = UIColor.red
let unselectedColor = UIColor.cyan

UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: unselectedColor,NSFontAttributeName: UIFont(name: "Gotham-Book", size: 10)!], for: .normal)
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: selectedColor,NSFontAttributeName: UIFont(name: "Gotham-Book", size: 10)!], for: .selected)

if let items = self.tabBar.items {
    for item in items {
        if let image = item.image {
            item.image = image.withRenderingMode( .alwaysOriginal )
            item.selectedImage = UIImage(named: "(Imagename)-a")?.withRenderingMode(.alwaysOriginal)
        }
    }
}

viewDidLoad之后:

   override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {

   if(item.title! == "title")
   {
    item.selectedImage = UIImage(named: "(Imagname)-a")?.withRenderingMode(.alwaysOriginal)

    }
    if(item.title! == "title")
    {
        item.selectedImage = UIImage(named: "(Imagname)-a")?.withRenderingMode(.alwaysOriginal)

    }
    if(item.title! == "title")
    {
        item.selectedImage = UIImage(named: "(Imagname)-a")?.withRenderingMode(.alwaysOriginal)

    }
    if(item.title! == "title")
    {
        item.selectedImage = UIImage(named: "(Imagname)-a")?.withRenderingMode(.alwaysOriginal)

    }
    if(item.title! == "title")
    {
        item.selectedImage = UIImage(named: "(Imagname)-a")?.withRenderingMode(.alwaysOriginal)

    }

}

在视图确实加载方法中,您必须设置所选图像,其他图像使用 RenderingMode 显示,在选项卡栏委托方法中,您根据标题设置所选图像

对于Swift 4.0 ,它现在更改为:

tabBarItem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.gray], for: .normal)
tabBarItem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.blue], for: .selected)

如果您的要求只是更改文本颜色,则不必对 UITabBarItem 进行子类化。 只需将上面的代码放在视图控制器的viewDidLoad函数中。

对于全局设置,将tabBarItem更改为UITabBarItem.appearance()

在 Swift 4.2 中:

UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: .normal)
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.red], for: .selected)

您可以设置 UIBarItem 的 tintColor :

UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.magentaColor()], forState:.Normal)
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.redColor()], forState:.Selected)

Swift 5 ios 13.2 中,TabBar 样式发生了变化,下面的代码工作 100%,经过测试。

在您的UITabBarController类中添加以下代码。

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let appearance = UITabBarAppearance()
        appearance.backgroundColor = .white

        setTabBarItemColors(appearance.stackedLayoutAppearance)
        setTabBarItemColors(appearance.inlineLayoutAppearance)
        setTabBarItemColors(appearance.compactInlineLayoutAppearance)

        setTabBarItemBadgeAppearance(appearance.stackedLayoutAppearance)
        setTabBarItemBadgeAppearance(appearance.inlineLayoutAppearance)
        setTabBarItemBadgeAppearance(appearance.compactInlineLayoutAppearance)

        tabBar.standardAppearance = appearance
 }

@available(iOS 13.0, *)
private func setTabBarItemColors(_ itemAppearance: UITabBarItemAppearance) {
    itemAppearance.normal.iconColor = .lightGray
    itemAppearance.normal.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.gray]

    itemAppearance.selected.iconColor = .white
    itemAppearance.selected.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.orange]
}

@available(iOS 13.0, *)
private func setTabBarItemBadgeAppearance(_ itemAppearance: UITabBarItemAppearance) {
    //Adjust the badge position as well as set its color
    itemAppearance.normal.badgeBackgroundColor = .orange
    itemAppearance.normal.badgeTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
    itemAppearance.normal.badgePositionAdjustment = UIOffset(horizontal: 1, vertical: -1)
}

你也可以这样做:

override func viewWillLayoutSubviews() {  
  if let items = self.tabBar.items {
    for item in 0..<items.count {
      items[item].image = items[item].image?.withRenderingMode(.alwaysOriginal)
            items[item].selectedImage = items[item].selectedImage?.withRenderingMode(.alwaysTemplate)
    }

可选的:

 UITabBar.appearance().tintColor = UIColor.red

我希望它会帮助你。

如果您想在按下时更改Tab Bar Item的图像,则此代码适用于Swift 4 复制粘贴到项目中命中的第一个viewDidLoad方法中

   let arrayOfImageNameForSelectedState:[String] = ["Image1Color", "Image2Color","Image3Color"]
   let arrayOfImageNameForUnselectedState: [String] = ["Image1NoColor","Image2NoColor","Image3NoColor"]


    print(self.tabBarController?.tabBar.items?.count)

    if let count = self.tabBarController?.tabBar.items?.count {
        for i in 0...(count-1) {
            let imageNameForSelectedState   = arrayOfImageNameForSelectedState[i]
            print(imageNameForSelectedState)
            let imageNameForUnselectedState = arrayOfImageNameForUnselectedState[i]
            print(imageNameForUnselectedState)
            self.tabBarController?.tabBar.items?[i].selectedImage = UIImage(named: imageNameForSelectedState)?.withRenderingMode(.alwaysOriginal)
            self.tabBarController?.tabBar.items?[i].image = UIImage(named: imageNameForUnselectedState)?.withRenderingMode(.alwaysOriginal)
        }
    }

年份:2020 iOS 13.3

将以下代码复制到AppDelegate.swift -> func didFinishLaunchingWithOptions

//Set Tab bar text/item fonts and size
let fontAttributes = [NSAttributedString.Key.font: UIFont(name: "YourFontName", size: 12.0)!]
UITabBarItem.appearance().setTitleTextAttributes(fontAttributes, for: .normal)
//Set Tab bar text/item color
UITabBar.appearance().tintColor = UIColor.init(named: "YourColorName")

这里开始

每个标签栏项目都有一个标题、选定的图像、未选定的图像和一个标记值。

使用图像色调(SelectedImageTintIntColor)字段在选择该选项卡时指定栏项的色彩颜色。 默认情况下,该颜色为蓝色。

斯威夫特 5:

let homeTab = UITabBarItem(title: "Home", image: UIImage(named: "YOUR_IMAGE_NAME_FROM_ASSETS")?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal), tag: 1)

斯威夫特 5.3

let vc = UIViewController()
vc.tabBarItem.title = "sample"
vc.tabBarItem.image = UIImage(imageLiteralResourceName: "image.png").withRenderingMode(.alwaysOriginal)
vc.tabBarItem.selectedImage = UIImage(imageLiteralResourceName: "image.png").withRenderingMode(.alwaysOriginal)
        
// for text displayed below the tabBar item
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.black], for: .selected)

从 Xcode 13.0 开始,您也可以在 UI 上设置此颜色:Select 选项卡栏,然后在 Inspector 中自定义 Standard 和 Scroll to Edge Appearance,在此项目下方,您将找到 Stacked 和 Inline 自定义选项。 如果您自定义 select,那么您将拥有“标题颜色”设置。 您必须将它们全部设置 (4)。

Xcode 检查器

只需在项目中添加一个新的 UITabBarController 引用。接下来在这个控制器中创建一个 UITabBar 的引用:

@IBOutlet weak var appTabBar: UITabBar!

在它的viewDidLoad() 中,只需在下面添加标题文本颜色

    appTabBar.tintColor = UIColor.scandidThemeColor()

对于图像

    tabBarItem = UITabBarItem(title: "FirstTab", image: UIImage(named: "firstImage"), selectedImage: UIImage(named: "firstSelectedImage"))

子类化您的 TabbarViewController 并在 ViewDidLoad 中放置以下代码:

 [UITabBarItem.appearance setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor darkGreyColorBT]} forState:UIControlStateNormal];
    [UITabBarItem.appearance setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor nightyDarkColorBT]} forState:UIControlStateSelected];

    self.tabBar.items[0].image  = [[UIImage imageNamed:@"ic-pack off@3x.png"]  imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.tabBar.items[0].selectedImage  = [[UIImage imageNamed:@"ic-pack@3x.png"]  imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.tabBar.items[1].image = [[UIImage imageNamed:@"ic-sleeptracker off@3x.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.tabBar.items[1].selectedImage  = [[UIImage imageNamed:@"ic-sleeptracker@3x.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.tabBar.items[2].image = [[UIImage imageNamed:@"ic-profile off@3x.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.tabBar.items[2].selectedImage  = [[UIImage imageNamed:@"ic-profile@3x.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

这是我拥有的最简单的工作解决方案

如果您想支持 iOS 13 及以上版本,请尝试此代码,因为设置 UItabBar 的方式与 iOS 13 完全不同。

        if #available(iOS 13, *) {
            let appearance = UITabBarAppearance()
            
//            appearance.backgroundColor = .white
            appearance.shadowImage = UIImage()
            appearance.shadowColor = .white
            
            appearance.stackedLayoutAppearance.normal.iconColor = .gray
            appearance.stackedLayoutAppearance.normal.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.gray]
//            appearance.stackedLayoutAppearance.normal.badgeBackgroundColor = .yellow
            
            appearance.stackedLayoutAppearance.selected.iconColor = .systemPink
            appearance.stackedLayoutAppearance.selected.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.systemPink]
            
            // set padding between tabbar item title and image
            appearance.stackedLayoutAppearance.selected.titlePositionAdjustment = UIOffset(horizontal: 0, vertical: 4)
            appearance.stackedLayoutAppearance.normal.titlePositionAdjustment = UIOffset(horizontal: 0, vertical: 4)
            
            self.tabBar.standardAppearance = appearance
        } else {
            // set padding between tabbar item title and image
            UITabBarItem.appearance().titlePositionAdjustment = UIOffset(horizontal: 0, vertical: 4)
            UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.gray], for: .normal)
            UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.systemPink], for: .selected)
        }

从 Xcode 14/iOS 16 开始,在UITabBarController子类中,您只需设置tabBartintColorunselectedItemTintColor属性:

tabBar.tintColor = 'some UI color'
tabBar.unselectedItemTintColor = 'some UI color'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM