5

I have a sheet that I put outside a foreach loop . When I click on Tapgesture the first time the results are blank, after the first time I get the correct data for every row I tap . I have read Sheet inside ForEach doesn't loop over items SwiftUI but it is still not working this is my code . If you look at my code I have a state variable called sharePost which on tap gets the value of value.post then the shareSheet toggle gets set to true . For some reason I can not get the value on very first tap . Does anyone have any suggestions on fixing this issue

struct TimeLineView: View {
    @Binding var model: [MainModel]
    @Binding var isMainView: MainViewEnum
    @State var shareSheet = false
    @State var PostIDState = 0
    @State var sharePost = ""

var body: some View {
        ZStack
        {

         let result = model.sorted {
                        $0.id! > $1.id!
                    }
                    
                    ForEach(result) { value in
                   HStack {
                            Image("share")
                              .resizable()
                              .frame(width: 28, height: 28)
                              .onTapGesture {
                                            sharePost = value.post
                                            shareSheet.toggle()
                     
                                             }

                        }
                    }

                 }.sheet(isPresented: $shareSheet) 
                  {
                     ShareView(message:"\(sharePost)" )
                  }
             }

        }
user1591668
  • 2,591
  • 5
  • 41
  • 84
  • 1
    Does this answer your question https://stackoverflow.com/a/64798254/12299030? (possible duplicate) – Asperi Jan 18 '21 at 17:20
  • 1
    Might be related with iOS 14 changes - see [iOS14 introducing errors with @State bindings](https://stackoverflow.com/q/63928736/8697793). What environment do you use? – pawello2222 Jan 18 '21 at 17:46
  • 1
    Yes it answers my question, thank you. I am using IOS 14 . – user1591668 Jan 19 '21 at 03:17

2 Answers2

5

Apparently, one of the workarounds for this is to use StateObject instead of State. Here's a Medium article that demonstrates the solution.

AnupamChugh
  • 1,779
  • 1
  • 25
  • 36
4

To fix this issue, one solution is to implement the sheet modifier in the following way:

.sheet(isPresented: Binding(
                get: { shareSheet },
                set: { shareSheet = $0 }
            )) {
                ShareView(message:"\(sharePost)" )
            }
  • 1
    Nice, worked for me! Was trying to not use 'sheet(item' but isPresented was giving me this first attempt problem, this answer works. – Alessandro Pace Apr 08 '23 at 17:09