-2

I am trying to display words in a Picker next to the selected option but the words are never displayed correctly. I want the user to be able to click the text to be able to open the Picker as well. I have tried putting the text outside the picker which leads to displaying correctly but the text is not clickable. I am using Xcode 13 Beta 5 and iOS15.

struct ContentView: View {
    @State var fruit = "Apple"
    let fruits = ["Apple","Orange","Pear","Grape"]
    
    var body: some View {
        HStack {
            Picker(selection: $fruit) {
                Text("Picked:")
                ForEach(fruits, id: \.self){ fruit in
                    Text(fruit)
                }
            } label: {
                Text("")
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Picture for Picker with text outside of Picker Picker

Tweaks made to fit what I asked are shown below. Any thing put inside label is now clickable.

Menu {
    Picker(selection: $fruit, label: EmptyView()) {
        ForEach(fruits, id: \.self) { fruit in
            Text(fruit)
        }
    }
} label: {
      HStack {
          Image(systemName: "hand.thumbsup.fill")
          Text("Picked: \(fruit)")
      }
}
runemonster
  • 177
  • 1
  • 11

1 Answers1

5

Use a Menu with a inline Picker as its content:

Menu {
    Picker(selection: $fruit, label: EmptyView()) {
        ForEach(fruits, id: \.self) { fruit in
            Text(fruit)
        }
    }
    .labelsHidden()
    .pickerStyle(InlinePickerStyle())
} label: {
    HStack {
        Text("Picked:")
        Text(fruit)
    }
}
Adam
  • 4,405
  • 16
  • 23
  • This works for what I need if I tweak it a little I wanted the Picked to be shown and clickable. I can add any combination of views inside of the Menu label and make the whole thing clickable. – runemonster Aug 23 '21 at 19:11
  • Correct, anything inside the Menu’s ‘label’ will be clickable. – Adam Aug 23 '21 at 19:51
  • This method seems to not auto center the list on the selected value. It's a problem with long lists which extend out of the screen. – Quentin Hayot Nov 25 '21 at 00:01