【发布时间】:2020-07-03 11:36:49
【问题描述】:
我正在尝试使用 CoreData 和 SwiftUI 创建一个小项目
我创建了 2 个简单实体,一个名为 Airport,属性为 icaoAPT,另一个名为 Briefing,属性为 note
两者之间的关系,每个机场应该有很多注意事项
在 contentView 上,我设法创建了一个列表,显示所有已插入的机场
import SwiftUI
struct ContentView: View {
@Environment(\.managedObjectContext) var managedObjectContext
//Lista aeroporti
@FetchRequest(
entity: Airport.entity(),
sortDescriptors: [ NSSortDescriptor(keyPath: \Airport.icaoAPT, ascending: true) ]
) var apt: FetchedResults<Airport>
var body: some View {
NavigationView {
List{
ForEach(apt, id: \.self) { airp in
NavigationLink(destination: DeatailsView(briefing: airp)) {
HStack{
Text(airp.icaoAPT ?? "Not Avail")
}
}
}
}.navigationBarTitle(Text("Aeroporti"))
.navigationBarItems(trailing: NavigationLink(destination: AddView(), label: {
Text("add data")
}))
}
}
}
在 addview 上我将数据添加到机场实体
import SwiftUI
struct AddView: View {
@State var aptICAO : String = ""
@Environment(\.presentationMode) var presentation
@Environment(\.managedObjectContext) var dbContext
var body: some View {
VStack{
TextField("ICAO", text: self.$aptICAO)
.textFieldStyle(RoundedBorderTextFieldStyle())
Button(action: {
let newAirport = Airport(context: self.dbContext)
newAirport.icaoAPT = self.aptICAO
do {
try self.dbContext.save()
self.presentation.wrappedValue.dismiss()
} catch {
print("errore nel salva")
}
}) {
Text("Save")
}
}.padding()
}
}
在 detailsView 上我想显示与该机场相关的注释,但我编写的代码不起作用,我觉得我应该在 detailsView 上放置一个 NSFetch 来过滤该机场的注释....但我没有知道怎么写。
我的详细信息查看:
import SwiftUI
struct DeatailsView: View {
@Environment(\.managedObjectContext) var dbContext
@Environment(\.presentationMode) var presentation
@State var briefing : Airport
@FetchRequest(
entity: Briefing.entity(),
sortDescriptors: []) var noteAPT: FetchedResults<Briefing>
var body: some View {
VStack{
ForEach(noteAPT, id: \.self) { dt in
Text(dt.note ?? "Nt avail")
}
}
.navigationBarTitle( Text(briefing.icaoAPT ?? "apt not avail"))
.navigationBarItems(trailing: NavigationLink(destination: AddNote(airport: briefing), label: {
Text("add Note")
}))
}
}
这里是我的 AddNote 视图:
struct AddNote: View {
@State var note : String = ""
@Environment(\.presentationMode) var presentation
@Environment(\.managedObjectContext) var dbContext
@State var airport : Airport
var body: some View {
VStack{
TextField("Note", text: self.$note)
.textFieldStyle(RoundedBorderTextFieldStyle())
Button(action: {
let newNOTE = Briefing(context: self.dbContext)
newNOTE.note = self.note
do {
try self.dbContext.save()
self.presentation.wrappedValue.dismiss()
} catch {
print("errore nel salva")
}
}) {
Text("Save Note for\(airport.icaoAPT ?? "NA")")
}
}.padding()
}
}
我总是看到我为每个机场添加的相同注释,但每个机场应该不同。
感谢您的帮助
【问题讨论】:
标签: swift xcode core-data swiftui nsfetchrequest