micah
micah

Reputation: 1248

SwiftUI tap picker like a button

Is it possible to make a SwiftUI picker tap like a button. The following only lets you set the picker if you tap on the text, but I would like to tap the picker like a button.

struct ContentView: View {
    @State var myvar: String = ""
    var body: some View {
        Picker(selection: $myvar, label:
            Text("Phone Type")) {
            Text("Home").tag(0)
            Text("Service").tag(1)
            Text("Work").tag(2)
            Text("Cell").tag(3)
            Text("Other").tag(4)
        }.padding().border(Color.gray)
    }
}

Thanks for any help!

Upvotes: 0

Views: 3511

Answers (2)

micah
micah

Reputation: 1248

@Asperi was right in their comment. The Menu is better than the picker when wanting it to display as a button. Here is a simple code example.

struct ContentView: View {
    @State var myvar: String = ""
    var body: some View {
        Menu {
            // This should be done in a ForEach loop
            Button("Home", action: {myvar="Home"})
            Button("Service", action: {myvar="Service"})
            Button("Work", action: {myvar="Work"})
            Button("Cell", action: {myvar="Cell"})
            Button("Other", action: {myvar="Other"})
        } label: {
            //THIS ALLOWS CLICKING TO OPEN ON THE BLUE BACKGROUND
            Text("ClickHere")
                .frame(width: 200, height: 100, alignment: .center)
                .background(Color.blue)
                .foregroundColor(Color.white)
        }
    }
}

Upvotes: 2

you could try this with .pickerStyle. Note that your tag(...) needs to match the type in myvar, so using string, like this:

struct ContentView: View {
    @State var myvar: String = ""
    var body: some View {
        Picker(selection: $myvar, label: Text("Phone Type")) {
            Text("Home").tag("Home")
            Text("Service").tag("Service")
            Text("Work").tag("Work")
            Text("Cell").tag("Cell")
            Text("Other").tag("Other")
        }
        .pickerStyle(.segmented)
        .padding().border(Color.gray)
    }
}

Upvotes: 1

Related Questions