-2

I have a problem when I load the NormDetailView of my app. It loads the default norm always instead of the selected norm by user, but after loading default one, it loads the norm selected by user.

Before that I was using NavigationLink and it was working perfectly how I wanted. I'm adding the code that I was using without Sheet for example:

VStack {
        List {
            ForEach(normsSearch) {norm in
                Section(header: Text(norm.title)) {
                    ForEach(norm.elements) { element in
                        NavigationLink(destination: NormDetailView(chosenNormElement: element)) {
                            Text(element.name)
                        }
                    }
                }
            }
        }

I know that it's always loading the default norm for the first time because I checked it with using breakpoint. I couldn't find any solutions and I want your help. I'm putting the codes that I'm using now below for your inspection. Thanks for any help in advance

//The bool that I used to control the NormDetailsView
@State var showingSheet = false

//I need to create this one to use at .sheet part
@State var chosenElement: NormElements = en103052

var body: some View {
    NavigationView {
        VStack {
            List {
                ForEach(normsSearch) {norm in
                    Section(header: Text(norm.title)) {
                        ForEach(norm.elements) { element in
                            Button(element.name) {
                                //I added this to pass "element" value to "chosenElement" that I created above
                                chosenElement = element
                                showingSheet.toggle()
                            }
                        }
                    }
                }
            }.sheet(isPresented: $showingSheet, content: {
                //I need to attach a chosenNormElement because I'm getting the file name from the button that clicked by user to open PDF file
                NormDetailsView(chosenNormElement: chosenElement)
            })
caneraltuner
  • 263
  • 1
  • 3
  • 12
  • 2
    Use `sheet(item:)` instead of `sheet(isPresented:)`. See https://stackoverflow.com/questions/66162219/swiftui-switch-sheet-on-enum-does-not-work – jnpdx Aug 26 '23 at 00:12

1 Answers1

0

Thanks to @jnpdx, I used sheet(item:) instead of sheet(isPresented:) and now my code is working. I would like to share my codes to how I solved my problem.

First, i changed chosenElement, I made it optional and made it equal to nil:

@State var chosenElement: NormElements? = nil

Then I changed to sheet(item:) down below:

.sheet(item: $chosenElement, content: { sheet in 
   SheetView(chosenNormElement: sheet)
})

That's how I solved my problem, thank you all and have a nice day

caneraltuner
  • 263
  • 1
  • 3
  • 12