Search code examples
swiftcocoamacos-big-surnsalert

NSAlert destructive button


As Big Sur came onto our Macs I noticed that destructive button's text in NSAlert controller are colored in red as shown in picture.

An example from the Apple's Message app

I wasn't able to find a way to bring this feature in my app.

Using the standard addButton(withTitle:) method we haven't any way to set its intent (such as default, cancel or destructive).

Can you give me any hint?

Thanks


Solution

  • To add to vadian’s answer:

    Seems like setting a button to destructive only works when the button is not the first one (and thus not the blue highlighted button). For everyone curious, this is how it could look in code:

    let alert = NSAlert()
    alert.messageText = "Alert Title"
    alert.alertStyle = .warning
    alert.addButton(withTitle: "Cancel")
    alert.addButton(withTitle: "Destructive Button")
        
    if #available(macOS 11.0, *) {
        alert.buttons.last?.hasDestructiveAction = true
    }
    

    The downside is that the user can’t accept the destructive action with enter and either has to click manually or select the button via tab (option has to be enabled in settings).