当editMode为.inactive时,如何使列表显示一组选定项;而当editMode为.active时,如何使所有可选选项均如此,以便用户可以更改一组选定项?这是我尝试过的:
import SwiftUI
struct SelectionView: View {
@Environment(\.editMode) var editMode
@State var selectedItems = Set<String>(["1-item", "2-item", "3-item", "4-item"])
let allItems = ["1-item", "2-item", "3-item", "4-item"]
var items: [String] {
if editMode?.wrappedValue == .inactive {
return Array(selectedItems)
}
else {
return allItems
}
}
var body: some View {
NavigationView {
List(items, id: \.self, selection: $selectedItems) { item in
Text(item)
}
.navigationBarItems(trailing: EditButton())
.navigationBarTitle("Items")
}
}
}
所选数组现在是无序的,因为它是从集合生成的,我最终希望以正确的顺序进行排列。但是我首先尝试使列表按原样工作。
答案 0 :(得分:0)
这里是对我有用的方法。不幸的是,由于List
内部细节(或错误)的原因,它并不完全好。
这个想法是切换List
的容器以根据所选项目过滤其中的一个,而切换本身取决于手动跟踪EditMode
无论如何,它都能正常工作(在Xcode 11.2 / iOS 13.2上以及在预览版中都经过测试)
struct SelectionView: View {
@State var editMode: EditMode = .inactive // ! Needed manual to track states
@State var selectedItems = Set<String>(["1-item", "2-item", "3-item", "4-item"])
let allItems = ["1-item", "2-item", "3-item", "4-item"]
var items: [String] {
allItems.filter { self.selectedItems.contains($0) }
}
@State var applyFilter = false
var body: some View {
NavigationView {
VStack {
List(applyFilter ? items : allItems, id: \.self,
selection: $selectedItems) { item in
Text(item)
}
.navigationBarItems(trailing: EditButton())
.navigationBarTitle("Items")
}
// .environment(\.editMode, $editMode) // << this is how it should be, but crash
.environment(\.editMode, Binding<EditMode>(get: { self.editMode },
set: {
self.editMode = $0
// !!! below is needed workaround, because applying filter directly
// on close EditMode result in crash due to cached List internals
// until switch EditMode animation is finished completely
if $0 == .inactive {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
self.applyFilter = true
}
} else {
self.applyFilter = false
}
}))
}
}
}