14

I'd like to make something like this NSAlert:
enter image description here

As you can see, the 'return' button is the second one. How can I do this?
Here's an example of the code that I use to create my NSAlert, but the first button gets the focus:

NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:@"Are you sure you want to disconnect?"];
[alert addButtonWithTitle:@"Disconnect"];
[alert addButtonWithTitle:@"Cancel"];
[alert runModal];

I want to focus the "Cancel" button. Any ideas? Thanks!

Pedro Vieira
  • 3,330
  • 3
  • 41
  • 76
  • You may be interested in this cocoa-dev thread: [Making the correct button the default button?](http://www.cocoabuilder.com/archive/cocoa/96603-making-the-correct-button-the-default-button.html) – jscs May 18 '13 at 19:06

2 Answers2

20

To change the key equivalents for the NSButton elements inside of the NSAlert object, you'll have to access the buttons directly (after creation and before -runModal) and change the key equivalents using the -setKeyEquivalent: method.

For example, to set the Disconnect to be ESC and the Cancel to be return, you would do the following:

NSArray *buttons = [alert buttons];
// note: rightmost button is index 0
[[buttons objectAtIndex:1] setKeyEquivalent: @"\033"];
[[buttons objectAtIndex:0] setKeyEquivalent:@"\r"];

before calling -runModal

gaige
  • 17,263
  • 6
  • 57
  • 68
  • The right most button("Disconnect") is at index 0. Its key is "\r" i.e. return, not ESC. I may get it wrong? – LShi Aug 06 '16 at 02:01
0

Swift 4

let alert = NSAlert()
alert.messageText = question
alert.informativeText = text
alert.alertStyle = .critical
let deleteButton = alert.addButton(withTitle: "Delete")
let cancelButton = alert.addButton(withTitle: "Cancel")
deleteButton.keyEquivalent = ""
cancelButton.keyEquivalent = "\r"
scum
  • 3,202
  • 1
  • 29
  • 27