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

da1*_*da1 8 ios swiftui xcode11

有什么方法可以在TabbedView选中或取消选中SwiftUI 中的选项卡项时更改它的图像?

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

  Text("Away").tabItem {
    Image("away")
    Text("Away")
  }.tag(1)
}
Run Code Online (Sandbox Code Playgroud)

我试过在网上搜索,但没有找到答案。我正在使用 Xcode 11 beta 4。

jku*_*chi 25

您可以使用条件/三元运算符并根据 $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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)