我有一个显示 CoreData FetchRequest 的列表,并且我有一个 Picker 可以更改列表的排序方式。我实现这个的当前方式看起来像:
struct ParentView: View {
enum SortMethod: String, CaseIterable, Identifiable {
var id: Self { self }
case byName = "Name"
case byDateAdded = "Date Added"
}
@State private var currentSortMethod = SortMethod.byName
var body: some View {
ItemListView(sortMethod: currentSortMethod) // See child view implementation below
.toolbar {
ToolbarItem(placement: .principal) {
Picker("Sort by", selection: $currentSortMethod) {
ForEach(SortMethod.allCases) { sortMethod in
Text(sortMethod.rawValue)
}
}
}
}
}
}
子视图看起来像:
struct ItemListView: View {
@Environment(\.managedObjectContext) private var managedObjectContext
@FetchRequest var items: FetchedResults<Item>
init(sortMethod: ParentView.SortMethod) {
let sortDescriptor: NSSortDescriptor
switch sortMethod {
case .byName:
sortDescriptor = NSSortDescriptor(keyPath: \Item.name, ascending: true)
case .byDateAdded:
sortDescriptor = NSSortDescriptor(keyPath: \Item.dateAdded, ascending: true)
}
_items = .init(
entity: Item.entity(),
sortDescriptors: [sortDescriptor],
predicate: nil,
animation: .default
)
}
var body: some View {
List {
ForEach(items) { item in
SingleItemView(item)
}
}
}
}
但是,当我更改排序选项时,列表不会为重新排序设置动画(可能是由于整个ItemListView
被重建。如果我在父视图中添加.animation(.default)
,ItemListView()
列表在重新排序时会动画,但从导航返回时也会有奇怪的动画其他视图。我似乎无法弄清楚我可以在哪里添加一个withAnimation { }
块。或者是否有更好的方法来解决这个问题,它对 SwiftUI 来说更自然,从而允许一些默认动画?