In the following code, I have a list that has a button in each row. What I want is to be able to pass the selected Fruit from the ContentView to the SecondView when the button is tapped. Right now I can present the SecondView but it's blank, it has no text in it, in other words, I don't see the text, Second View: [fruit name]. Please note that I cannot use the NavigationLink(destination:) because I'm already using it to go to a details view when the rows are tapped.
How can I pass the selected fruit to the Second View when the button on each row is tapped?
Fruit Object
struct Fruit: Identifiable{
var id = UUID()
var name:String
}
Content View:
struct ContentView: View {
@State private var secondViewIsPresented = false
var fruits = [Fruit(name: "Apple"), Fruit(name: "Orange")]
var body: some View {
List{
ForEach(fruits){ fruit in
HStack{
Text(fruit.name)
Button("Tap Me"){
secondViewIsPresented.toggle()
SecondView(selectedFruit: fruit)
}
.frame(width:150, height: 35)
.background(Color.blue)
.buttonStyle(BlueButton())
}
}
}
.sheet(isPresented: $secondViewIsPresented){
// Here I cannot access the selected fruit
}
}
}
// style to make the button in the row work properly
// I'm showing it just for reference.
struct BlueButton: ButtonStyle {
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.scaleEffect(configuration.isPressed ? 2 : 1)
}
}
Second View
struct SecondView: View {
var selectedFruit: Fruit
var body: some View {
Text("Second View: \(selectedFruit.name)")
}
}