is there a way to get a destructive Button
style in SwiftUI?
I know I can do this for a ContextMenu
, but I did not find a way for "normal" Button
.
Cheers
From iOS 15 You can (and you should!) assign a Role
to each button like:
Button("Delete", role: .destructive) {
deleteSomething()
}
Assigning the role to a button helps the system to apply the proper style for each context that uses the button (for example like this example for a context menu)
You can create a combination of modifiers to create the needed style.
VStack {
Button("Plain", role: .none, action: { })
.buttonStyle(PlainButtonStyle())
Button("Automatic", role: .none, action: { })
.buttonStyle(.automatic)
Button("Log out", role: .cancel, action: { })
.buttonStyle(BorderedButtonStyle())
.tint(.yellow)
// with controlSize
Button("Cancel", role: .cancel, action: { })
.buttonStyle(.borderless)
.controlSize(.small)
.tint(.yellow)
Button("Delete", role: .destructive, action: { })
.buttonStyle(.bordered)
.controlSize(.regular)
// with controlProminence
Button(role: .destructive, action: { }, label: {
Text("Exit").frame(maxWidth: .infinity)
})
.buttonStyle(.bordered)
.controlSize(.large)
.controlProminence(.increased)
//with BorderedShape
Button(role: .destructive, action: { }, label: {
Text("Wow shape").frame(maxWidth: .infinity)
})
.buttonStyle(BorderedButtonStyle(shape: .capsule))
.controlSize(.large)
.controlProminence(.increased)
.tint(.purple)
}
For Button
:
Button("Tap") {
// do something
}
.foregroundColor(.red)
For Alert
:
Alert(
title: Text("Hi"),
message: Text("Do it?"),
primaryButton: .cancel(Text("Cancel")),
secondaryButton: .destructive(Text("Delete")) {
// do something
}
)
And similarly for ActionSheet
.