Seems hard to believe that this could be so difficult - is the standard AppKit option of something like a square button and type 'toggle' not available under swiftUI or is there a modifier somewhere that can be used to achieve the same thing.
How do I create a simple toggle button in the macOS toolbar with SwiftUI
I'm currently using this code within the .toolbar modifier for a view that is embedded within a NavigationView...
and this is my AppData class that conforms to ObservableObject that I use to store the value for isEditing...
Alternatively you could use the @State property wrapper within your View struct that contains the NavigationView...
I haven't attempted to use the Toggle View before, but to answer this question I just used it successfully in a macOS target I'm writing in SwiftUI...
The benefit of using Toggle over Button, is that when the toggle value for isOn = true, the Toggle has a slightly darker background to demonstrate the selected state. This would have to be added manually to Button to achieve the same effect.
I'll be using Toggle.
Code Block .toolbar { ToolbarItem(placement: .primaryAction) { Button(action: appData.isEditing.toggle()) { Label(appData.isEditing ? "Done" : "Edit", systemImage: appData.isEditing ? "pencil.circle.fill" : "pencil.circle") } .disabled(<< insert your own logic here >>) .help("Edit the selected record") } }
and this is my AppData class that conforms to ObservableObject that I use to store the value for isEditing...
Code Block final class AppData: ObservableObject { @Published var isEditing: Bool = false }
Alternatively you could use the @State property wrapper within your View struct that contains the NavigationView...
Code Block struct yourView: View { @State private var isEditing = false ... }
I haven't attempted to use the Toggle View before, but to answer this question I just used it successfully in a macOS target I'm writing in SwiftUI...
Code Block Toggle(isOn: $appData.isEditing) { Label(appData.isEditing ? "Done" : "Edit", systemImage: appData.isEditing ? "pencil.circle.fill" : "pencil.circle") } .disabled(<< insert your own logic here >>) .help("Edit the selected record")
The benefit of using Toggle over Button, is that when the toggle value for isOn = true, the Toggle has a slightly darker background to demonstrate the selected state. This would have to be added manually to Button to achieve the same effect.
I'll be using Toggle.