如何让NSAlert的第二个按钮成为返回按钮?

Ped*_*ira 14 macos cocoa objective-c nsalert

我想做这样的事情NSAlert:
在此输入图像描述

如您所见,"返回"按钮是第二个按钮.我怎样才能做到这一点?
这是我用来创建我的代码的示例NSAlert,但第一个按钮获得焦点:

NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:@"Are you sure you want to disconnect?"];
[alert addButtonWithTitle:@"Disconnect"];
[alert addButtonWithTitle:@"Cancel"];
[alert runModal];
Run Code Online (Sandbox Code Playgroud)

我想关注"取消"按钮.有任何想法吗?谢谢!

gai*_*ige 17

要更改对象NSButton内部元素的等效键NSAlert,您必须直接访问按钮(创建之后和之前-runModal),并使用该-setKeyEquivalent:方法更改等效键.

例如,设置Disconnect成ESC和Cancel要回报,你会做以下几点:

NSArray *buttons = [alert buttons];
// note: rightmost button is index 0
[[buttons objectAtIndex:1] setKeyEquivalent: @"\033"];
[[buttons objectAtIndex:0] setKeyEquivalent:@"\r"];
Run Code Online (Sandbox Code Playgroud)

在打电话之前 -runModal