我目前正在尝试使用导航链接将值的数组传递到详细信息视图中。但是,每当我尝试传递数组时,指定用于显示导航链接的文本函数调用都会给我“表达式类型不明确且没有更多上下文的错误”错误。当我传递简单的单个值时,这不是问题,但是我需要能够在详细信息视图中显示数组中的每个元素。
struct Item: Identifiable{
let id=UUID()
let name:String
}
struct Group: Identifiable{
let id:Int
let thing:String
let items:[Item]
}
//the "Item" objects are currently placeholders.
var groups = [
Group(id: 0,
thing:"Tops",
items:[Item(name:"first"), Item(name:"second"), Item(name:"third")]),
Group(id: 2,
thing:"Jeans",
items:[Item(name:"first"), Item(name:"second"), Item(name:"third")]),
Group(id: 3,
thing:"Skirts",
items:[Item(name:"first"), Item(name:"second"), Item(name:"third")]),
Group(id: 4,
thing:"Shoes",
items:[Item(name:"first"), Item(name:"second"), Item(name:"third")]),
Group(id: 5,
thing:"Pajamas",
items:[Item(name:"first"), Item(name:"second"), Item(name:"third")]),
Group(id: 6,
thing:"Jackets",
items:[Item(name:"first"), Item(name:"second"), Item(name:"third")]),
Group(id: 7,
thing:"Hats",
items:[Item(name:"first"), Item(name:"second"), Item(name:"third")]),
Group(id: 8,
thing:"Jewelry",
items:[Item(name:"first"), Item(name:"second"), Item(name:"third")])
]
var body: some View {
List(groups){ group in
NavigationLink(destination : ClosetDetailView(items: group.items)){
//location of error
Text(group.thing)
}
}
.background(Color.pinkish)
.navigationBarTitle("Categories")
}
}
struct PlaceholderView:View {
var body:some View{
Text("placeholder")
}
}
struct ClosetDetailView:View {
struct Item: Identifiable{
let id=UUID()
let name:String
}
var items:[Item]
var body : some View{
List(items){ item in
HStack{
Text(item.name)
}
}
}
}
答案 0 :(得分:0)
首先,要启用到详细视图的导航,应将列表嵌入到NavigationView中:
struct ContentView: View {
var body: some View {
NavigationView {
List(groups) { group in
NavigationLink(destination: ClosetDetailView(items: group.items)) {
Text(group.thing)
.listRowBackground(Color.red)
}
}
.navigationBarTitle("Categories")
}
}
}
如果将参数传递给函数时发生错误,通常会出现错误“表达式的类型是模棱两可的,没有更多上下文”。在这种情况下,您的壁橱详细视图需要一个Item数组。问题是您在ClosetDetailView内部和外部定义了一个项目结构。将项目传递到ClosetDetailView时发生此错误,可能会导致整个NavigationLink出错。删除ClosetDetailView中的Struct,错误消失:
struct ClosetDetailView:View {
var items:[Item]
var body : some View{
List(items){ item in
HStack{
Text(item.name)
}
}
}
}