Search code examples
swiftuipickertabview

SwiftUI Picker view disappears in TabView


Simple SwiftUI TabView with two tabs, with a simple Picker view used on each tab. When the app starts, the Picker is visible and updates the variable. Select the second tab, and the Picker vanishes.

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

Solution

  • In such cases (when you have absolutely equal views) it is better to make them unique with .id.

    So your case is fixed, say, with the following

      Picker(selection: $kind, label: EmptyView()) {
        ForEach(0 ..< names.count) {index in
          Text(names[index]).tag(index)
        }
      }
      .pickerStyle(SegmentedPickerStyle())
      .id(UUID().uuidString)