簡體   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