我想添加一个新的清单标。 为此,要求你从一艘船主中挑选一艘船舶物体。 如果尚未设立船舶,则促使你先填上一张船号,然后在船只上加后撤销该船。
如果我开车,船只已经存在,一切照旧。 然而,如果还没有船只从船上挑选,则在船上打上新号(NewView)号船,并正确地向船级添加新物体。 当它返回新通风港时,它现在向该船检查后发现该船。 页: 1 如果I ("vessel= (vessel)”>
,此时,I 收到vessel = <Vessel: 0x6000017d07c0> (entity: <null> id: (null); data: <fault>)
,并试图挽救 app。
However if I click on the picker and re-select the item that looks like its already selected, then it works fine. How can I force the NewInventoryView to refresh the picker choices for vessel once it returns from adding one on NewVesselView?
我的守则如下:
import SwiftUI
struct InventoryNewView: View {
@Environment(.managedObjectContext) private var viewContext
@State private var showSheetVessel = false
@FetchRequest(
sortDescriptors: [SortDescriptor(.name)])
var vessels:FetchedResults<Vessel>
@Environment(.dismiss) var dismiss
@State var name = ""
@State var vessel = Vessel()
var body: some View {
NavigationView {
ScrollView {
VStack(alignment: .leading){
Grid(alignment: .leading) {
GridRow {
Text("Name:")
TextField("Inventory item", text: $name)
}
.padding(.bottom, 5)
GridRow {
Text("Assigned to:")
if vessels.isEmpty == false {
Picker("", selection: $vessel) {
ForEach(vessels) { (vessel: Vessel) in
Text(vessel.name)
.tag(vessel)
}
}
}
else {
Text("Add Vessel")
.fontWeight(.semibold)
.foregroundColor(Color.red)
}
Button(action: {
self.showSheetVessel.toggle()
}) {
Image(systemName: "plus.circle")
.font(.footnote)
}.sheet(isPresented: $showSheetVessel) {
VesselNewView()
}
}
.padding(.bottom, 5)
}
}
.navigationTitle("Add New Inventory")
.navigationBarItems(
trailing:
Button("Add") {
addInventory()
dismiss()
}
.disabled(name.isEmpty)
)
}
}
func addInventory() {
// Add the item into Core Data
let inventory = Inventory(context: viewContext)
inventory.id = UUID()
inventory.name = name
inventory.vessel = vessel
vessel.addToInventory(inventory)
do {
try viewContext.save()
}
catch {
}
}
}
}