在 TabView 中更改所选选项卡项目的颜色,而不使用 .tint 或 .accentColor

问题描述 投票:0回答:1

.tint
.accentColor
影响的不仅仅是选项卡栏,还渗透到切换、导航栏按钮项目、滑块等,并且单独设置每个组件重音以避免这种情况似乎是一个巨大的痛苦。如何更改所选项目的颜色而不影响任何其他组件?

我尝试在选项卡项目视图上设置

.foregroundColor
/
.foregroundStyle
(不起作用)。

我也尝试在 init 中设置它,但没有明显的效果:

init {
    let tabBarAppearance = UITabBarAppearance()
    tabBarAppearance.configureWithDefaultBackground()
    tabBarAppearance.stackedLayoutAppearance.selected.iconColor = UIColor.red
    tabBarAppearance.stackedLayoutAppearance.selected.titleTextAttributes = [.foregroundColor: UIColor.red]
    tabBarAppearance.stackedLayoutAppearance.normal.iconColor = UIColor.lightGray
    tabBarAppearance.stackedLayoutAppearance.normal.titleTextAttributes = [.foregroundColor: UIColor.lightGray]
    UITabBar.appearance().standardAppearance = tabBarAppearance
    UITabBar.appearance().scrollEdgeAppearance = tabBarAppearance
}

如果可能的话,我不想在叠加层中使用定制的选项卡栏。有没有什么方法可以在本机选项卡栏中实现此目的而不更改任何其他组件的颜色?

swift swiftui swiftui-tabview
1个回答
0
投票

您正在设置

stackedLayoutAppearance
的属性,这是标签栏在常规水平尺寸级别 iPad 上使用的外观,因此您不会在 iPhone 上看到效果。

您还应该设置

inlineLayoutAppearance
compactInlineLayoutAppearance
的属性。

// do this in onAppear, which is main actor-isolated
.onAppear {
    let tabBarAppearance = UITabBarAppearance()
    tabBarAppearance.configureWithDefaultBackground()
    
    @MainActor
    func configureAppearance(_ appearance: UITabBarItemAppearance) {
        appearance.selected.iconColor = UIColor.red
        appearance.selected.titleTextAttributes = [.foregroundColor: UIColor.red]
        appearance.normal.iconColor = UIColor.lightGray
        appearance.normal.titleTextAttributes = [.foregroundColor: UIColor.lightGray]
    }
    
    configureAppearance(tabBarAppearance.stackedLayoutAppearance)
    configureAppearance(tabBarAppearance.inlineLayoutAppearance)
    configureAppearance(tabBarAppearance.compactInlineLayoutAppearance)
    
    UITabBar.appearance().standardAppearance = tabBarAppearance
    UITabBar.appearance().scrollEdgeAppearance = tabBarAppearance
}
© www.soinside.com 2019 - 2024. All rights reserved.