I am passing an object between views using @Binding from the previous view. The struct is designed as such:
struct Topping: Identifiable {
let name: String
let price: Double
var amount: Int
let id = UUID()
}
// Ex. Topping(name: "Cheese", price: 3.00, amount: 0)
struct ToppingList: Identifiable {
let name: String
var list: [Topping]
var id: String {
name+"menu\(menu.indices)"
}
}
// Ex. ToppingList(name: "Cheeses", menu: [Topping(...), Topping(...)])
struct MenuItem: Identifiable {
let name: String
let description: String
let size: [String]
let image: String
let price: [Double]
var toppings: [ToppingList]
var id: String {
"_"+name
}
}
// Ex. MenuItem(...toppings: [Topping(name: "Cheese", price: 3.00, amount: 0), Topping(name: "Pepperoni", price: 3.00, amount: 0)])
I pass the list of toppings to the view, and with a stepper hope to increment or decrement the amount of toppings (per unique topping). The problem that arises is when this happens, the view crashes to my home page.
The code for the views is separated into 2 - one for displaying the rows of steppers in a form, and the child view - for the individual rows.
// This view is the main view,
struct ToppingCategoryView: View {
@Binding var menuItem: MenuItem
// Pretend this is the MenuItem passed:
// MenuItem(...toppings: ToppingList(name: "Cheeses", list: [Topping(name: "Mozza", price: 3.00, amount: 0), Topping(name: "Parmesan", price: 3.00, amount: 0)]))
var body: some View {
VStack {
Form {
ForEach($menuItem.toppings) { $menu in
Section (menu.name){
ExtraToppingsView(toppingsList: $menu.list)
}
}
}
}
}
The following view is where the stepper and @Binding variable is. I wish to increase the amount of toppings. Doing so, dismisses the view, but still increases the variable. If I load the view again, it displays correctly. Not sure why the view is dismissed. No error messages or warnings I could reproduce or find.
struct ExtraToppingsView: View {
@Binding var toppingsList: [Topping]
var body: some View {
VStack {
ForEach($toppingsList) { $topping in
Stepper {
Text("\(topping.amount)")
} onIncrement: {
topping.amount += 1
if topping.amount >= 4 { topping.amount = 3 }
} onDecrement: {
topping.amount -= 1
if topping.amount <= -1 { topping.amount = 0 }
}
}
}
}
}
I figured out what the issue is, it seems to be some kind of bug or something else I am not aware of.
It relates to using NESTED navigation links.
To fix this, I simply add .isDetailLink(False)
to EVERY NavigationLink in the project. This fixed the issue.