Reputation: 2893
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)" )
}
}
}
Upvotes: 10
Views: 2432
Reputation: 477
Swift 5
Use this view modifier when you need to present a modal view with content from a custom data source.
.sheet(item: $sharePost, content: { sharePost in
ShareView(message:"\(sharePost)" )
})
Upvotes: 0
Reputation: 549
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)" )
}
Upvotes: 13
Reputation: 1899
Apparently, one of the workarounds for this is to use StateObject
instead of State
. Here's a Medium article that demonstrates the solution.
Upvotes: 8