【发布时间】:2021-04-30 04:05:46
【问题描述】:
我正在尝试制作一个餐馆位置列表,每个位置都显示在 EateryRow 中,可以单击该位置移动到 EateryDetail 页面,但是通过执行此代码,我收到一个错误,我认为这是相关的NavigationLink 参数的语法。
另外:我发现了这个question,它似乎和我有同样的问题,但仍然没有答案。
import SwiftUI
struct EateryList: View {
@Binding var eateries: [Eatery]
var body: some View {
NavigationView {
VStack {
List {
ForEach(eateries) {
NavigationLink(destination: EateryDetail(eatery: $eateries[identifiedBy: $0])) { //error here
EateryRow(eatery: $eateries[identifiedBy: $0])
}
}
.onMove {
eateries.move(fromOffsets: $0, toOffset: $1)
EateriesApp.save()
}.onDelete {
eateries.remove(atOffsets: $0)
EateriesApp.save()
}
}
.navigationTitle("Favourite Eateries")
.navigationBarItems(leading: EditButton(), trailing: Button( action: add)
{
Image(systemName: "plus")
}
)
.listStyle(InsetGroupedListStyle())
}
}
}
func add() {
eateries.append(Eatery(name: "Eatery", location: "Insert location here", notes: "Insert notes here", reviews: ["Insert reviews here"], url: "https://i.imgur.com/y3MMnba.png"))
EateriesApp.save()
}
}
我在使用 NavigationLink 时收到此错误:
未命名的参数 #2 必须在参数“目标”之前
为了进一步清楚,这是我在 EateryDetail 和 EatertyRow 视图中使用“eatery”变量的方式:
struct EateryDetail: View {
@Binding var eatery: Eatery
struct EateryRow: View {
@Binding var eatery: Eatery
这是我在 Eatery.swift 文件中定义的 Eatery 代码:
import Foundation
struct Eatery: Codable, Identifiable {
var id = UUID()
var name: String
var location: String
var notes: String
var reviews: [String] = []
var url: String = ""
}
在eateriesApp.swift 中也定义了这个:
import SwiftUI
@main
struct EateriesApp: App {
@State var model: [Eatery] = EateriesApp.model
static var model: [Eatery] = {
guard let data = try? Data(contentsOf: EateriesApp.fileURL),
let model = try? JSONDecoder().decode([Eatery].self, from: data) else {
return [elCaminoCantina, theFineDine, nightBites, theRiverRodeo, theCozyKitchen, theElegantEatery]
}
return model
}()
static var modelBinding: Binding<[Eatery]>?
var body: some Scene {
EateriesApp.modelBinding = $model
return WindowGroup {
ContentView(eateries: $model)
}
}
【问题讨论】:
-
为什么是
identifiedBy?顺便说一句,您可以发布Eatery的代码吗? -
使用
ForEach(eateries) { eaterie in而不是$0。
标签: swift xcode foreach swiftui swiftui-navigationlink