Hi,
I am making a list app with SwiftUI. In the view which shows the list's items, each item has an info button which allows the user to edit the item. However, when I pass the item to that view, it does not pass the right item.
For example, I have a list of items:
Item 5 [Info Button]
Item 4 [Info Button]
Item 3 [Info Button]
Item 2. [Info Button]
Item 1. [Info Button]
If I tap on the Info Button for any one of the items, it will only show Item 5 in the Detail Edit View.
Here's the code:
I am making a list app with SwiftUI. In the view which shows the list's items, each item has an info button which allows the user to edit the item. However, when I pass the item to that view, it does not pass the right item.
For example, I have a list of items:
Item 5 [Info Button]
Item 4 [Info Button]
Item 3 [Info Button]
Item 2. [Info Button]
Item 1. [Info Button]
If I tap on the Info Button for any one of the items, it will only show Item 5 in the Detail Edit View.
Here's the code:
Code Block swift struct ItemsView: View { @Environment(\.managedObjectContext) private var viewContext @ObservedObject var group: ItemGroup @State private var showingDetailView = false var body: some View { ScrollView { VStack(alignment: .leading) { ForEach(group.ongoingItems) { item in ItemRow(for: item) .padding() } } func ItemRow(for item: Item) -> some View { HStack(spacing: 10) { ... Text(item.wrappedName) .fontWeight(.light) Spacer() Button(action: { showingDetailView.toggle() }, label: { Image(systemName: "info.circle").imageScale(.large) }) .sheet(isPresented: $showingDetailView, content: { NavigationView { ItemDetailView(selectedItem: item) } }) } }
Code Block swift struct ItemDetailView: View { @Environment(\.managedObjectContext) var viewContext @ObservedObject var selectedItem: Item ...
Having multiple sheets controlled by a single @State variable is not recommended.
Please try something like this:
Please try something like this:
Code Block struct ItemsView: View { @Environment(\.managedObjectContext) private var viewContext @ObservedObject var group: ItemGroup @State private var showingDetailView = false @State var selectedItem: Item = Item() var body: some View { ScrollView { VStack(alignment: .leading) { ForEach(group.ongoingItems) { item in itemRow(for: item) .padding() } //... } //... } .sheet(isPresented: $showingDetailView, content: { ItemInfoSheet(item: $selectedItem) }) } func itemRow(for item: Item) -> some View { HStack(spacing: 10) { //... Text(item.wrappedName) .fontWeight(.light) Spacer() Button(action: { selectedItem = item showingDetailView.toggle() }, label: { Image(systemName: "info.circle").imageScale(.large) }) } } //... } struct ItemInfoSheet: View { @Binding var item: Item var body: some View { NavigationView { ItemDetailView(selectedItem: item) } } }