PAYATHON 2026

SwiftUI TabView 未选中 SF Symbol 图标颜色如何设置?

数据小许

结论

SwiftUI 的 TabView 标签栏由 UIKit 的 UITabBar 承载。要设置未选中标签的图标颜色,可以配置 UITabBarAppearance 中的 normal.iconColor,并设置 unselectedItemTintColor。.tint(.red) 控制选中态颜色,不会将未选中图标设为蓝色。

题目代码还有一处语法错误:

appearance.stackedLayoutAppearance.normal.iconColor = .systemBlue.

.systemBlue 后多了一个句点,删除即可。

设置未选中图标和文字颜色

创建 TabView 前配置标签栏外观,例如在 App.init() 中设置:

import SwiftUI

@main
struct TestApp: App {
    init() {
        let appearance = UITabBarAppearance()
        appearance.configureWithDefaultBackground()

        let normal = appearance.stackedLayoutAppearance.normal
        normal.iconColor = .systemBlue
        normal.titleTextAttributes = [
            .foregroundColor: UIColor.systemBlue
        ]

        let tabBar = UITabBar.appearance()
        tabBar.standardAppearance = appearance
        tabBar.unselectedItemTintColor = .systemBlue

        if #available(iOS 15.0, *) {
            tabBar.scrollEdgeAppearance = appearance
        }
    }

    var body: some Scene {
        WindowGroup {
            TabView {
                SettingsView()
                    .tabItem {
                        Label("Received", systemImage: "tray.and.arrow.down")
                    }

                SettingsView()
                    .tabItem {
                        Label("Sent", systemImage: "tray.and.arrow.up")
                    }

                SettingsView()
                    .tabItem {
                        Label("Account", systemImage: "person.crop.circle")
                    }
            }
            .tint(.red)
        }
    }
}

normal.iconColor 设置未选中图标的颜色,normal.titleTextAttributes 设置未选中文字的颜色,unselectedItemTintColor 则明确指定未选中项目的 tint。iOS 15 及更新版本还可以设置 scrollEdgeAppearance,避免标签栏处于滚动边缘状态时显示不同颜色。

注意事项

Label 上的 .symbolRenderingMode(.monochrome) 用于控制 SF Symbol 的渲染模式,不会设置 UITabBar 未选中项目的 tint。只需更改颜色时,通常不必在每个标签项上单独设置它。

外观代理应在标签栏创建前配置。如果项目中的其他代码也设置了 UITabBar 外观,请检查是否有后续配置覆盖这些值。

备注:内容仅供参考。