选择时更改一个选项的颜色

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

我制作了一个示例 TabView,其accentColor为.white。如何在选择时将 View3 的 .tabItem 的颜色更改为蓝色,而不将其他 tabItems 更改为蓝色? 所以View1和View2的tabItem在选中时是白色的,View3的tabItem是蓝色的。

struct HomeScreen: View {
    var body: some View {
        TabView {
            View1()
                .tabItem {
                    Label("View1", systemImage: "command")
                }
            View2()
                .tabItem {
                    Label("View2", systemImage: "option")
                }
            View3()
                .tabItem {
                    Label("View3", systemImage: "alt")
                }
        }
        .accentColor(.white)
    }
}
swiftui
1个回答
0
投票

如果将标签值与每个选项卡相关联,则可以根据选择设置强调色。

顺便说一句,

.accentColor
已弃用,建议使用
.tint
代替:

struct HomeScreen: View {
    @State private var selection = 1
    var body: some View {
        TabView(selection: $selection) {
            View1()
                .tag(1)
                .tabItem {
                    Label("View1", systemImage: "command")
                }
            View2()
                .tag(2)
                .tabItem {
                    Label("View2", systemImage: "option")
                }
            View3()
                .tag(3)
                .tabItem {
                    Label("View3", systemImage: "alt")
                }
        }
        .tint(selection == 3 ? .blue : .white)
    }
}

Animation

© www.soinside.com 2019 - 2024. All rights reserved.