【问题标题】:How to make the NSAlert's 2nd button the return button?如何使 NSAlert 的第二个按钮成为返回按钮?
【发布时间】:2013-05-13 17:37:47
【问题描述】:

我想做这样的东西NSAlert:

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

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

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

【问题讨论】:

标签: objective-c macos cocoa nsalert


【解决方案1】:

要更改NSAlert 对象内NSButton 元素的等效键,您必须直接访问按钮(在创建之后和-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之前

【讨论】:

  • 最右边的按钮(“断开连接”)在索引 0 处。它的键是“\r”,即返回,而不是 ESC。我可能弄错了?
【解决方案2】:

斯威夫特 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-04-20
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    • 2018-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多