我有一个从
@FetchRequest
检索到的 CoreData 对象列表。我希望根据对象的属性对列表进行重新排序;一个Bool
。
在下面的代码中,当您单击行项目时,视图会重建并且顺序会更改,但这种情况会立即发生,并且没有动画,尽管在获取请求上有动画。
我也尝试过向
List
和 RowView
添加动画,但这也不起作用。
import SwiftUI
struct RowView: View {
@ObservedObject var place: Place
var body: some View {
Button {
place.visit()
try? DataController.shared.container.viewContext.save()
} label: {
HStack {
Text(place.wrappedName)
Spacer()
place.visited ? Image(systemName: "checkmark.circle.fill") : Image(systemName: "checkmark.circle")
}
}
}
}
struct ListDetailView: View {
let list: PlaceList
@FetchRequest var places: FetchedResults<Place>
init(list: PlaceList) {
self.list = list
_places = .init(
entity: Place.entity(),
sortDescriptors: [NSSortDescriptor(keyPath: \Place.visited, ascending: true)],
predicate: NSPredicate(format: "list = %@", list),
animation: .default
)
}
var body: some View {
VStack {
Text(self.list.wrappedName)
.font(.headline)
List {
ForEach(places) { place in
RowView(place: place)
}
}
.listStyle(.plain)
}
}
}
你需要一个动画块,例如
withAnimation {
place.visit()
// save if you like
}
struct ListDetailView: View {
let list: PlaceList
@FetchRequest var places: FetchedResults<Place>
init(list: PlaceList) {
self.list = list
_places = .init(
entity: Place.entity(),
sortDescriptors: [NSSortDescriptor(keyPath: \Place.visited, ascending: true)],
predicate: NSPredicate(format: "list = %@", list),
animation: .default
)
}
var body: some View {
VStack {
Text(self.list.wrappedName)
.font(.headline)
List {
ForEach(places) { place in
RowView(place: place)
.animation(.default) // Add animation modifier here
}
}
.listStyle(.plain)
}
}
}