Some more specific details in case that helps.
The key structures are set up in the following pattern.
struct MyApp: App {
let viewModel = MyViewModel()
var body: some Scene {
Window {
...
}
.environment(viewModel)
.commands {
MyCommands(viewModel: viewModel)
}
}
}
struct MyCommands: Commands {
let viewModel: MyViewModel()
@FocusedValue(\.selectedEntryID) private var focusedID: UUID?
var body: some Commands {
CommandGroup(...) {
Button(...) {
viewModel.doSomething(with id: focusedID)
}
...
}
}
}
struct ContentView: View {
@Environment(MyViewModel.self) var viewModel
var body: some View {
Table(viewModel.records, selection: $viewModel.selectedID) {
TableColumn("Column A") { record in
TextField("", text: Binding(
get: { record.field1 ?? "" },
set: { newValue in
record.field1 = newValue
}
...
}
.focusedSceneValue(\.selectedEntryID, viewModel.selectedEntryID)
I can verify that there is an UndoManager available to ContentView via @Environment(.undoManager) in the view and adding a button. But it's only present inside the button action, and is nil in .onAppear, for instance, so I don't have an opportunity to inject it into the viewModel before a menu-driven Add action.
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags: