How would you share a common Button(action: { some action })
across Views?
I have:
VStack {
ToolbarViewA(states)
TableViewB(states)
...
}
View
initializer states include $data
& $selection,
so each View
has the 'same' data.
I would like a Button
in a contextMenu
on a Table
in TableViewB
to perform the identical click action as a Button
in ToolbarViewA
.
How would you approach this challenge?
I am interested in learning how to think SwiftUI so I would appreciate your thoughts! I really like v5, it is gelling with me. Thank you Apple!
What I would do:
- Define States class
class States: ObservableObject {
@Published var data: = // some type of data and initial value
@Published var selection : = "" // some type of data and initial value
}
- define (even at main app level) a State object for states : States
- declare it in the environment
@main
struct TheApp: App {
@StateObject var states = States()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(states) // Essential, to pass value to environment
}
}
}
- create a View holding the Button using this environment object
struct CommonButton: View {
@EnvironmentObject var states: States
var body: some View {
Button(action: {
// using states
}) {
Text("Button title") // That could be specific to the Button: declare a var for Title that will be passed as parameter
}
}
}
Use CommonButton where needed