我在一个视图中有列表,选择一行后,想导航到另一个视图。我正在尝试将“LocationInfra”(一个核心数据实体)传递给另一个 ConfigProfileView。当我通过 NavigationLink 调用 ConfigProfileView 时,SummaryView 中出现两个错误
由于“私有”保护级别,“ConfigProfileView”初始化程序无法访问
无法将类型“FetchedResults.Element”(又名“LocationInfra”)的值转换为预期参数类型“Binding
struct summaryView: View {
@State public var selectedLocationInfra: LocationInfra? = nil
var body: some View {
NavigationView {
ScrollView(showsIndicators: false){
ForEach(locationProfiles) { locationProfile in
NavigationLink (""){
ConfigProfileView(locationInfra: selectedLocationInfra) // get two errors here
}
label: do {
HStack {
// some code here
}.onTapGesture {
selectedLocationInfra = locationProfile
}
}
}
}
.navigationTitle("Summary")
}
}
要显示的视图
struct ConfigProfileView: View {
@Environment(\.managedObjectContext) private var viewContext
@Binding private var locationInfra: LocationInfra?
NavigationView {
ScrollView(showsIndicators: false) {
VStack (alignment: .leading ) {
Text(locationInfra?.locationName!)
}
}
}
}
如何修复错误?
我假设你的数组可能是这样的:
struct SummaryView: View {
var locationProfiles: [LocationInfra] = [
.init(index: 0, locationName: "US"),
.init(index: 1, locationName: "UK"),
.init(index: 2, locationName: "SG")
]
var body: some View {
NavigationView {
ScrollView(showsIndicators: false) {
ForEach(locationProfiles) { locationProfile in
NavigationLink {
ConfigProfileView(locationInfra: locationProfile)
} label: {
Text("Index: \(locationProfile.index)")
}
}
}
.navigationTitle("Summary")
}
}
}
然后在
ConfigProfileView
,只是为了显示:
struct ConfigProfileView: View {
@Environment(\.managedObjectContext) private var viewContext
var locationInfra: LocationInfra?
var body: some View {
NavigationView {
ScrollView(showsIndicators: false) {
VStack (alignment: .leading ) {
Text(locationInfra?.locationName ?? "unknown")
}
}
}
}
}
输出: