SwiftUI:如何在TabbedView中更改所选项目的图像

问题描述:

在选择或未选择SwiftUI的 TabbedView 中,是否可以更改选项卡项目的图像?

Is there any way to change the image of a tab item in SwiftUI's TabbedView when it's selected or unselected?

TabbedView(selection: $selection) {
  Text("Home").tabItem {
    Image(systemName: "house")
    Text("Home")
  }.tag(0)

  Text("Away").tabItem {
    Image("away")
    Text("Away")
  }.tag(1)
}

我尝试在网上搜索,但未找到答案.我正在使用Xcode 11 beta4.

I've tried searching on the web but no answers were found. I'm using Xcode 11 beta 4.

您可以使用条件/三元运算符并根据 $ selection

You can use a conditional/ternary operator and render an image depending on the $selection

请参阅示例:

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

    var body: some View {
        TabView(selection: $selection) {
            Text("Home")
                .tabItem {
                    selection == 0 ? Image(systemName: "house.fill") : Image(systemName: "house")
                    Text("Home")
                }
                .tag(0)

            Text("Away")
                .tabItem {
                    selection == 1 ? Image(systemName: "a.circle.fill") : Image(systemName: "hand.raised.fill")
                    Text("Away")
                }
                .tag(1)
        }
    }
}