LisekKL
LisekKL

Reputation: 171

Make Picker default value a placeholder

Is it possible to set a placeholder text for a Swift Picker? I've been trying to search for a helpful answer but I haven't been successful so far.

Currently, when passing available list values to the Picker, I also pass it a default value to start with. However, this default value is treated the same as if the user picked it. What I'm trying to achieve is that the default value should be grayed out (like regular placeholders for standard textfields) and when the user opens the picker that value would 'disappear' as default forcing the user to pick something from the list (but without losing the range) -

So for example, if I have a picker for values between 1-200 and I set my placeholder to 100 the picker would still show this value when you open it (to avoid scrolling from the beginning) but it wouldn't be directly taken as the target value unless the user actually selects it.

Upvotes: 6

Views: 2408

Answers (2)

Roland Lariotte
Roland Lariotte

Reputation: 3498

You can have a Placeholder value by having a if statement before your ForEach within your SwiftUI picker.

The idea is to give to the @State var selection a value on which the placeholder will be held. If this value changes to an expected selection, the placeholder value disappears.

struct ContentView: View {

  @State private var selection = "Placeholder"

  var body: some View {
    Picker("Food", selection: $selection) {
      if selection == "Placeholder" {
        Text("Select ...").tag("Placeholder")
      }

      ForEach(foods, id: \.id) {
        Text($0.name).tag($0.name)
      }
    }.pickerStyle(.menu)
  }
}

let foods: [Food] = [
  .init(name: "Pasta"),
  .init(name: "Burger"),
  .init(name: "Salad")
]

struct Food {
  let id = UUID()
  let name: String
}

Upvotes: 0

David Zulaica
David Zulaica

Reputation: 388

A Menu may be a better option than a Picker in this instance.

Menu("Label") {
    Button("Menu Item", action: menuAction)
    Button("Other Menu Item", action: otherMenuAction)
}

Menu Documentation

Upvotes: 1

Related Questions