Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI destructive Button style

Tags:

button

swiftui

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

like image 896
gurehbgui Avatar asked Feb 16 '26 03:02

gurehbgui


2 Answers

iOS 15

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)

More customization

You can create a combination of modifiers to create the needed style.

Demo

Demo

Code for above example:

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)
}
like image 185
Mojtaba Hosseini Avatar answered Feb 19 '26 20:02

Mojtaba Hosseini


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.

like image 40
Yonat Avatar answered Feb 19 '26 20:02

Yonat