I have a View that is composed with a child view that is vended from a user selected object, presented as a sheet in a containing view. The Title/Address/Port in the screen shot below is from a single view and then the parent view has the Ok/Cancel buttons (The reasons for them to be separate is that I will need to reuse the vended settings views in another context which will have other settings and will have its own buttons)
I simply want the behavior that if the user presses cancel all edits are abandoned, and if the user presses Ok the values are persisted. Essentially in the child view I have:
@ObservedObject viewModel: ViewModel
@State addressEditValue: String
@State portEditValue: String
var body : some View {
VStack {
Text("Enter the server address and port")
.font(.title)
HStack {
Text("Address:")
TextField("Address", text: $addressEditValue)
.textContentType(.URL)
Text("Port:")
TextField("Port", value: $portEditValue, formatter: NumberFormatter())
}
}
.onAppear {
addressEditValue = viewModel.address
portEditValue = viewModel.port
}
}
In the container view I have:
.sheet(isPresented: $isSettingsSheetPresented, content: {
VStack {
ChildView
HStack {
Spacer()
Button {
isTimingSettingsPresented.toggle()
} label: {
Text("Cancel")
}
Button {
// instruct child view to persist itself here
isTimingSettingsPresented.toggle()
} label: {
Text("Ok")
}
.buttonStyle(.borderedProminent)
}
}
})
I’ve tried having the Child view conform to a protocol with a Submit function, but I only seem to be able to vend the settings view as an AnyView, which is type erasing the view. When I attempt to cast the view, it always fails:
if let childView = ChildView as? SubmittableViewProtocol
I’ve also tried to use published variables between the two views and respond to their onChange modifiers, but the ‘work’ I need to do once its submitted ends up called before the onChange is responded to.
This seems like it should be a simple thing to abandon or persist changes for a settings sheet in SwiftUI, but alas I’m out of ideas. Am I missing something obvious and simple here? Its very possible I’m not thinking a reactive way here, so any help is appreciated.
3