6

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

gurehbgui
  • 14,236
  • 32
  • 106
  • 178

2 Answers2

22

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)
}
Mojtaba Hosseini
  • 95,414
  • 31
  • 268
  • 278
4

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.

Yonat
  • 4,382
  • 2
  • 28
  • 37