簡體   English   中英

為 iOS 中的不同 UITabBarItem 設置不同的文本 colors 15

[英]Setting of different text colors for different UITabBarItem's in iOS 15

更新到iOS 15后,我這樣實現了UITabBar配置:

    let backgroundColor = UIColor.grey
    let selectedItemTextColor = UIColor.blue
    let unselectedItemTextColor = UIColor.black
    
    if #available(iOS 15, *) {
        let tabBarAppearance = UITabBarAppearance()
        tabBarAppearance.backgroundColor = backgroundColor
        tabBarAppearance.stackedLayoutAppearance.selected.titleTextAttributes = [.foregroundColor: selectedItemTextColor]
        tabBarAppearance.stackedLayoutAppearance.normal.titleTextAttributes = [.foregroundColor: unselectedItemTextColor]
        tabBar.standardAppearance = tabBarAppearance
        tabBar.scrollEdgeAppearance = tabBarAppearance
    } else {
        UITabBarItem.appearance().setTitleTextAttributes([.foregroundColor: selectedItemTextColor], for: .selected)
        UITabBarItem.appearance().setTitleTextAttributes([.foregroundColor: unselectedItemTextColor], for: .normal)
        tabBar.barTintColor = backgroundColor
    }

這適用於 iOS 15 及更舊版本。

但是在我的項目中,我需要為選項卡欄項目之一設置選定/未選定的文本顏色,這與其他項目不同。 在運行時設置它。

有 5 個選項卡欄項目。 在某些時候,我需要這種行為:其中四個應該有藍色/黑色文本顏色(對於選定/未選定狀態),一個應該有紅色/綠色。

直到iOS 15,我用這段代碼設置了每時每刻所需物品的colors:

let indexOfItemToChange = 4
tabBar.items[indexOfItemToChange].setTitleTextAttributes([.foregroundColor: UIColor.red], for: .selected)
tabBar.items[indexOfItemToChange].setTitleTextAttributes([.foregroundColor: UIColor.green], for: .normal)

update 更新到 iOS 15 后沒有效果。 我試過這樣設置:

let indexOfItemToChange = 4
tabBar.items[indexOfItemToChange].standardAppearance?.stackedLayoutAppearance.normal.titleTextAttributes = [.foregroundColor: UIColor.green]
tabBar.items[indexOfItemToChange].standardAppearance?.stackedLayoutAppearance.selected.titleTextAttributes = [.foregroundColor: UIColor.red]

但它也沒有效果。 即使在設置標簽欄項目 colors 之前,我為每個標簽欄項目設置了 UITabBar 外觀:

tabBar.items.forEach {
$0.standardAppearance = standardAppearance
$0.scrollEdgeAppearance =  scrollEdgeAppearance
}

有人遇到過這個問題嗎? 有什么建議嗎?

附言。 在我的項目中沒有 xibs 和故事板。 所以我只需要以編程方式解決我的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM