问题描述
我有一个显示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 { }
父视图,列表在重新排序时会显示动画,但是从其他视图导航时,列表也会有怪异的动画。我似乎无法弄清楚在哪里可以添加{{1}}块,或者是否有更好的方法这样做对SwiftUI来说更自然,因此允许一些默认动画?
解决方法
绑定可以附带动画,因此请尝试以下操作(或使用所需的任何动画参数)
Picker("Sort by",selection: $currentSortMethod.animation()) // << here !!