如何为选中/未选中使用不同的选项卡项目?

问题描述

如何为选中和未选中的标签创建不同的标签项?例如,我想使用不同的图像并将所选文本设为粗体。

这就是我所拥有的:

struct ContentView: View {
    @Scenestorage("selectedTab") private var selectedTab = 0

    var body: some View {
        TabView(selection: $selectedTab) {
            Text("Content 1")
                .tabItem {
                    Label("First",systemImage: "alarm")
                        .accessibilityHint("Something 1")
                }
            Text("Content 2")
                .tabItem {
                    Label("Second",systemImage: "calendar")
                        .accessibilityHint("Something 2")
                }
        }
    }
}

有没有一种内置的方法可以做到这一点,因为在选项卡内我无法确定它是否是选定的。

解决方法

使用带有标记的 selectedTab 并使用 selectedTab 条件更改标签图像。

对于字体,您可以使用 UITabBarAppearance()

struct ContentView: View {
    @State private var selectedTab = 0

    init() {
        // Set font here of selected and normal
        let appearance = UITabBarAppearance()
        appearance.stackedLayoutAppearance.normal.titleTextAttributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 10)]
        appearance.stackedLayoutAppearance.selected.titleTextAttributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 15)]
        UITabBar.appearance().standardAppearance = appearance
    }
    
    var body: some View {
        TabView(selection: $selectedTab) {
            Text("Content 1")
                .tabItem {
                    Label("First",systemImage: selectedTab == 0 ? "alarm" : "alarm_unselected") //<-- Here
                        .accessibilityHint("Something 1")
                }.tag(0) //<-- Here
            Text("Content 2")
                .tabItem {
                    Label("Second",systemImage: selectedTab == 1 ? "calendar" : "calendar_unselected") //<-- Here
                        .accessibilityHint("Something 2")
                }.tag(1) //<-- Here
        }
    }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...