在 iOS 13 中,UITabBarItem 的 standardAppearance 应用于所有其他项目

fra*_*yan 6 uitabbaritem uitabbar ios

我正在尝试在 iOS 13 上做一件简单的事情 -最后一个选项卡栏项目应始终以不同的颜色显示

我尝试使用新UITabBarItem.standardAppearance成员。这是我的代码:

// first, set the default colors for the whole tab bar
let color = Style.Color.tabItem
let text = [NSAttributedString.Key.foregroundColor: color]
let selectedColor = Style.Color.tabItemSelected
let selectedText = [NSAttributedString.Key.foregroundColor: selectedColor]

let barAppearance = UITabBarItemAppearance()

barAppearance.normal.iconColor = color
barAppearance.disabled.iconColor = color
barAppearance.selected.iconColor = selectedColor
barAppearance.focused.iconColor = selectedColor

barAppearance.normal.titleTextAttributes = text
barAppearance.disabled.titleTextAttributes = text
barAppearance.selected.titleTextAttributes = selectedText
barAppearance.focused.titleTextAttributes = selectedText

tabBar.standardAppearance.stackedLayoutAppearance = barAppearance
tabBar.standardAppearance.inlineLayoutAppearance = barAppearance
tabBar.standardAppearance.compactInlineLayoutAppearance = barAppearance
tabBar.standardAppearance.backgroundColor = Style.Color.tabBar

// now, for the last item set special colors
if let lastItem = tabBar.items?.last {
    let specialColor = Style.Color.tabItemSpecial
    let specialText = [NSAttributedString.Key.foregroundColor: specialColor]
    let specialSelectedColor = Style.Color.tabItemSpecialSelected
    let specialSelectedText = [NSAttributedString.Key.foregroundColor: specialSelectedColor]

    let itemAppearance = UITabBarItemAppearance()

    itemAppearance.normal.iconColor = specialColor
    itemAppearance.disabled.iconColor = specialColor
    itemAppearance.selected.iconColor = specialSelectedColor
    itemAppearance.focused.iconColor = specialSelectedColor

    itemAppearance.normal.titleTextAttributes = specialText
    itemAppearance.disabled.titleTextAttributes = specialText
    itemAppearance.selected.titleTextAttributes = specialSelectedText
    itemAppearance.focused.titleTextAttributes = specialSelectedText

    let itemBarAppearance = UITabBarAppearance()

    itemBarAppearance.stackedLayoutAppearance = itemAppearance
    itemBarAppearance.inlineLayoutAppearance = itemAppearance
    itemBarAppearance.compactInlineLayoutAppearance = itemAppearance
    itemBarAppearance.backgroundColor = Style.Color.tabBar

    lastItem.standardAppearance = itemBarAppearance
}
Run Code Online (Sandbox Code Playgroud)

预期行为:

所有选项卡项目始终tabItem/tabItemSelected颜色显示,最后一个选项卡项目始终tabItemSpecial/tabItemSpecialSelected颜色显示。

实际行为:

当选择除最后一项之外的任何一项时,所有选项卡项都显示在tabItem/中tabItemSelected包括最后一项!当我选择最后一个选项卡栏项目时,它的standardAppearance样式也适用于所有其他选项卡栏项目!所以他们都使用tabItemSpecial/tabItemSpecialSelected配色方案。

难道我做错了什么?或者也许我误解了新的 API,并且没有办法让一个选项卡栏项目始终具有不同的颜色?

小智 1

这是预期的行为。您不是自定义特定选项卡栏项目的外观,而是自定义该项目为当前选定项目时选项卡栏的显示方式。