Whenever I try delete an item from the list it automatically pops back up again, however the list itself does update and delete (I checked with a print statement). When I close the app and re-open it, it has deleted, but it won't delete immediately, is there something I am missing or have not spotted that anyone else can?
NavigationView {
VStack {
List {
ForEach(UserDefaults.standard.stringArray(forKey: "names")!, id: \.self) { name in
Group {
NavigationLink(destination: PersonView(name: name)) {
Text(name)
}
}
}.onDelete(perform: delete)
}.navigationBarTitle("Names")
}
}
The Delete function:
func delete(at offsets: IndexSet) {
names.remove(atOffsets: offsets)
UserDefaults.standard.set(names, forKey: "names")
}
The 'names' variable is declared further up as
@State public var names: [String] = []
that updates every time a new name is added (this works). And the new name also gets added to User Defaults (this also works).
CodePudding user response:
Just use names
in your ForEach
and load them using onAppear
method. Something like:
NavigationView {
VStack {
List {
ForEach(names, id: \.self) { name in
Group {
NavigationLink(destination: PersonView(name: name)) {
Text(name)
}
}
}.onDelete(perform: delete)
}.navigationBarTitle("Names")
}
}.onAppear{
names = UserDefaults.standard.stringArray(forKey: "names") ?? []
}