SwiftUI Picker视图在TabView中消失

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

带有两个选项卡的简单SwiftUI TabView,每个选项卡上都使用一个简单的Picker视图。应用启动时,选择器可见,并更新变量。选择第二个选项卡,并且选择器消失。

let names = ["Fred", "Wilma", "Betty", "Barney"]

struct WordPickerView: View {
  @State var kind: Int = 0

  var body: some View {
    VStack {
      Text(names[kind])
      Picker(selection: $kind, label: EmptyView()) {
        ForEach(0 ..< names.count) {index in
          Text(names[index]).tag(index)
        }
      }.pickerStyle(SegmentedPickerStyle())
    }
  }
}

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

    var body: some View {
        TabView(selection: $selection){
            WordPickerView()
                .font(.title)
                .tabItem {
                    VStack {
                        Image("first")
                        Text("First")
                    }
                }
                .tag(0)
            WordPickerView()
                .font(.title)
                .tabItem {
                    VStack {
                        Image("second")
                        Text("Second")
                    }
                }
                .tag(1)
        }
    }
}
swiftui picker tabview
1个回答
0
投票

在这种情况下(当您拥有绝对相等的视图时,最好用.id使其唯一。

因此,您的情况已经确定,例如,以下内容

  Picker(selection: $kind, label: EmptyView()) {
    ForEach(0 ..< names.count) {index in
      Text(names[index]).tag(index)
    }
  }
  .pickerStyle(SegmentedPickerStyle())
  .id(UUID().uuidString)
© www.soinside.com 2019 - 2024. All rights reserved.