Josh
Josh

Reputation: 685

SwfitUI - Cannot open sheet from a button that is a picker option

I want to open navigate to a view where I can add another picker option.

I tried the followings:


Picker(NSLocalizedString("Pick an option", comment: ""), selection: $value, content: {
            ForEach(options, id: \.self){ option in
            Text(option).tag(option)
            }
            Button(action: {
                sheetIsPresented.toggle()
            }, label: {
                Image(systemName: "plus")
            })
            .sheet(isPresented: $sheetIsPresented){
                AddView()
            }
        })

A button does show at the end of the options.

However, when the button is clicked, nothing happened. AddView() doesn't show up...

Is there a way to make this work?

Upvotes: 0

Views: 240

Answers (2)

try this approach, as shown in this example code:

struct ContentView: View {
    @State var sheetIsPresented = false
    @State var options = ["item-1","item-2","item-3"]
    @State var value = "item-1"
    
    var body: some View {
        VStack (spacing: 88){
            Picker(NSLocalizedString("Pick an option", comment: ""), selection: $value) {
                ForEach(options, id: \.self){ option in
                    Text(option).tag(option)
                }
            }
            Button(action: { sheetIsPresented.toggle() }) {
                Image(systemName: "plus")
            }
            .sheet(isPresented: $sheetIsPresented) {
                AddView(options: $options)
            }
        }
    }
}

struct AddView: View {
    @Binding var options: [String]
    
    var body: some View {
        // add some random option
        Button(action: { options.append(UUID().uuidString) }) {
            Image(systemName: "plus")
        }
    }
}

Upvotes: 1

micah
micah

Reputation: 1248

You can open a sheet with a menu if you put the .sheet on the menu element

example:

struct TestView: View {
    @State var sheetIsPresented: Bool = false
    var body: some View {
        Menu("Actions") {
            Button(action: {
                sheetIsPresented.toggle()
            }, label: {
                Image(systemName: "plus")
            })
        }
        .sheet(isPresented: $sheetIsPresented){
            VStack{
                Text("Hello")
            }
        }
    }
}

Upvotes: 0

Related Questions