我有一个模型,例如,它是标签云和项目模型:
struct TagCloud: Identifiable, Hashable{
var id: Int
let tag: String
static func tagCloud() -> [TagCloud]{
return [ TagCloud(id: 01, tag:"Green"),
TagCloud(id: 02, tag:"Blue"),
TagCloud(id: 03, tag:"Red")]
}
}
struct TaggedItem: Identifiable, Hashable{
var id: Int
let tag: String
let item: String
static func taggedItems() -> [TaggedItem]{
return [ TaggedItem(id: 01, tag:"Green", item: "Tree"),
TaggedItem(id: 02, tag:"Blue", item: "Sky"),
TaggedItem(id: 03, tag:"Red", item: "Apple")...]
}
}
我有一堂课来“包含”当前选定的项目:
class SelectedItems: ObservableObject {
@Published var currentlySelectedItems:[TaggedItem] = []
func changeData(forTag tag: String ){
let currentSelection = TaggedItem. taggedItems()
let filteredList = cardCollection.filter { $0.tag == tag }
currentlySelectedItems = filteredList
}
}
在父视图中,我从云中选择一个标签:
struct ParentView: View {
let tagCloud = TagCloud.tagCloud()
@ObservedObject var currentSelection : TaggedItem = TaggedItem()
@State var navigationTag:Int? = nil
var body: some View {
NavigationLink(destination: ChildView(), tag: 1, selection: $tag) {
EmptyView()
}
VStack{
ScrollView(.horizontal, content: {
HStack(spacing: 20){
ForEach( self.tagCloud, id: \.self) { item in
VStack{
Button(action: {
self. currentSelection.changeData(forTag: item.tag )
self.navigationTag = 1
}){
Text(item.tag)
}.buttonStyle(PlainButtonStyle())
..
}
子视图包含ObservedObject。附带说明,我也将其设置为EnvironmentObject。
struct ChildView: View {
@ObservedObject var currentItems : SelectedItems = SelectedItems()
var body: some View {
VStack{
ScrollView(.horizontal, content: {
HStack(spacing: 20){
ForEach( currentItems.currentlySelectedItems, id: \.self) { item in
...
问题:
我用init()尝试了很多东西。我尝试将选定的标签传递给孩子,然后在init()本身中进行过滤,但是由于绑定到类的需要而受阻。我在其他地方阅读过,尝试使用第二个模型,该模型将由FIRST模型更新以触发视图刷新。
通过父视图选择创建此过滤列表并使列表在子视图中可用的正确方法是什么?
答案 0 :(得分:1)
这部分应该重新考虑:
let tagCloud = TagCloud.tagCloud()
@ObservedObject var currentSelection : TaggedItem = TaggedItem()
^^ is a struct, it cannot be observed !!!
@ObservedObject
必须仅应用于@ObservableObject
,就像您对SelectedItems
一样,因此这里可能需要围绕ObservableObject
的另一个TaggedItem
视图模型包装器。 / p>