3

I have a ForEach loop with a sheet opening when user taps on a row. The data on the sheet opened is based on which row did the user select. My code:

@State private var showMoodModal = false
@State var activeMoodForModal = 0

...

ForEach(moodEntries, id: \.self) { entry in
    MoodTableViewCard(entry: entry).onTapGesture {
        self.activeMoodForModal = moodEntries.lastIndex(of: entry) ?? 0
        self.showMoodModal.toggle()
    }
}.sheet(isPresented: $showMoodModal) {
    MoodEntryModalView(entry: moodEntries[self.activeMoodForModal], isShown: self.$showMoodModal)
  }

The problem is no matter which row user selects on the first tap, it creates a MoodEntryModalView with entry: moodEntries[0]. If you dismiss the sheet and try to tap on another row it works fine. But if you relaunch the app the first try will always create the MoodEntryModalView with entry: moodEntries[0] no matter which row did you tap. How do I fix this?

Hekes Pekes
  • 1,175
  • 2
  • 12
  • 28
  • Does this answer your question https://stackoverflow.com/a/63089069/12299030? or https://stackoverflow.com/a/63217450/12299030? – Asperi Sep 25 '20 at 15:50
  • @Asperi I don't see much difference between this answer and my code which is not working, except I use Int instead of String. So still no idea. – Hekes Pekes Sep 25 '20 at 16:17
  • Tried to recreate and it is working for me – davidev Sep 25 '20 at 16:37
  • Looks like it works because of using $ in "item: $selected" when creating a sheet. In my code I need to send sheet a MoodEntry object so I use moodEntries[self.activeMoodForModal] and I don't see where can I put $ there. Is there any workaround here? – Hekes Pekes Sep 25 '20 at 17:13
  • 2
    now you use two states: one for selection, another for sheet activation. with `sheet(item:` modifier you need only one state - item - it can be anything Hashable, sheet is activated on that state change. It is explicitly modifier for such cases as yours and by references are the same - just try them in code, not in mind. – Asperi Sep 25 '20 at 17:19
  • 2
    Thanks, sheet(item: modifier solved it. – Hekes Pekes Sep 27 '20 at 18:45
  • 1
    @Asperi I can't believe took me a long time for figuring out this. @_@ – Yoon Lee Sep 04 '21 at 05:24

0 Answers0