1

如何为选定和未选定的选项卡创建不同的选项卡项?例如,我想使用不同的图像并将所选文本加粗。

这就是我所拥有的:

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")
                }
        }
    }
}

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

4

1 回答 1

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
        }
    }
}
于 2021-02-09T02:58:41.007 回答