I created a small SwiftData project, hosting a list with an .onDelete modifier.
In order to filter the list I extracted the list into a separate ListView and set the filter using the init method.
But I found no way to use the .onDelete modifier from inside the ListView.
I guess the modelContext from the ContentView is missing in the ListView, but I wasn’t able to make it available.
The sample data contains user12, user13, user22.
ContentView
struct ContentView: View {
@Environment (.modelContext) var modelContext
@State private var filteringList = false
var body: some View {
NavigationStack {
VStack {
ListView(filterByUserName: filteringList ? "1" : "user")
}
.toolbar {
Button("Filter list") {
filteringList.toggle()
}
}
}
}
}
ListView
struct ListView: View {
@Query var users: [UserModel]
init(filterByUserName: String) {
_users = Query(filter: #Predicate<UserModel> { user in user.name.contains(filterByUserName)},
sort: UserModel.name)
}
var body: some View {
List {
ForEach(users) { user in
Text(user.name)
}
//How can I use .onDelete in ListView?
// .onDelete(perform: { indexSet in
// deleteUser(at: indexSet)
// })
}
}
}
Mat Fetsch is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.