如何使用SwiftUI和CoreData@FetchRequest为动态列表排序设置动画

问题描述

我有一个显示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 !!

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...