2013-05-18 66 views
12

我想做出这样的事情NSAlert
enter image description here如何使NSAlert的第二个按钮成为返回按钮?

正如你所看到的,“返回”按钮是第二个。我怎样才能做到这一点?
下面的代码的例子,我用它来创建我的NSAlert,但第一个按钮获得焦点:

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

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

+0

之前,你可能有兴趣在这可可-dev的线程:[使正确的按钮成为默认按钮?](http://www.cocoabuilder.com/archive/cocoa/96603-making-the-correct-button-the-default-button.html) –

回答

17

要更改键当量为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

完美地工作!非常感谢你! –

+0

最右边的按钮(“断开”)在索引0处。它的键是“\ r”,即返回,而不是ESC。我可能弄错了? – LShi

相关问题