Show back button in Picker content

Viewed 170

I have a view with hidden navigation bar, but I need to show the navigation bar with back button when user select a value from picker.

When I add a leading button, my code shows all country texts as one item instead of making each Text in separate selectable row.

Any idea how to fix this issue?

VStack{
    Form {
        Picker(selection: $selectedCountry, label: HStack {
            Text("Country")
        }) {
            ForEach(0 ..< countries.count) {
                Text(self.countries[$0])
            }
            .navigationBarItems(leading: BackButton())
            .navigationBarBackButtonHidden(true)
            .navigationBarHidden(false)
        }
        .navigationBarHidden(true)
        .navigationBarBackButtonHidden(false)
    }
}.navigationBarTitle("")
.navigationBarHidden(true)

enter image description here

1 Answers

Applying modifiers to dynamic container, ie. ForEach, you convert it into one view, so picker shows only one combined view.

Here is possible solution - attach needed modifiers only to first item of picker (tested with Xcode 12 / iOS 14)

 Form {
      Picker(selection: $selectedCountry, label: HStack {
            Text("Country")
      }) {
            ForEach(0 ..< countries.count) {
                if 0 == $0 {
                    Text(self.countries[$0])
                        .navigationBarItems(leading: BackButton())
                        .navigationBarBackButtonHidden(true)
                        .navigationBarHidden(false)
                } else {
                    Text(self.countries[$0])
                }
            }
      }
      .navigationBarHidden(true)
      .navigationBarBackButtonHidden(false)
 }
Related