Reputation: 131
I'm trying to find the reason why .listRowBackground
is not updated when a new item has been added to the list. Here is my code sample:
@main
struct BGtestApp: App {
@ObservedObject var viewModel = ViewModel()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(viewModel)
}
}
}
struct ContentView: View {
@EnvironmentObject var vm: ViewModel
var body: some View {
NavigationView {
List {
ForEach(vm.items, id: \.self) { item in
NavigationLink {
DetailView().environmentObject(vm)
} label: {
Text(item)
}
.listRowBackground(Color.yellow)
}
}
}
}
}
struct DetailView: View {
@EnvironmentObject var vm: ViewModel
var body: some View {
Button("Add new") {
vm.items.append("Ananas")
}
}
}
TIA for you help!
Upvotes: 1
Views: 434
Reputation: 156
You can force the list to refresh when you cone back to the list. You can tag an id for your list by using .id()
. Here is my solution:
struct ContentView: View {
@EnvironmentObject var vm: ViewModel
@State private var viewID = UUID()
var body: some View {
NavigationView {
List {
ForEach(vm.items, id: \.self) { item in
NavigationLink {
DetailView()
.environmentObject(vm)
} label: {
Text(item)
}
}
.listRowBackground(Color.yellow)
}
.id(viewID)
.onAppear {
viewID = UUID()
}
}
}
}
Hope it's helpful for you.
Upvotes: 4
Reputation: 131
The solution I found is not ideal, but should work. What I did is made items to be @State
variable :
struct ContentView: View {
@EnvironmentObject var vm: ViewModel
@State var items: [String] = []
var body: some View {
NavigationView {
VStack {
List {
ForEach(items, id: \.self) { item in
NavigationLink {
DetailView().environmentObject(vm)
} label: {
RowView(item: item)
}
.listRowBackground(Color.yellow)
}
}
.onAppear {
self.items = vm.items
}
}
}
Upvotes: 0