14

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

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

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

我想关注“取消”按钮。有任何想法吗?谢谢!

4

2 回答 2

18

要更改对象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"];

打电话之前-runModal

于 2013-05-18T19:08:31.727 回答
0

斯威夫特 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"
于 2019-03-07T02:01:55.047 回答