苹果最初的HIG(遗憾的是现在从网站上消失了)说:
对话框中最右边的按钮,即操作按钮,是用于确认警报消息文本的按钮。动作按钮通常(但并非总是)是默认按钮
就我而言,我有一些破坏性操作(例如擦除磁盘),需要“安全”确认对话框,如下所示:
最糟糕的选择是创建一个对话框,其中最右边的按钮将变为“请勿擦除”按钮,而其左边的一个按钮(通常为“取消”按钮)将变为“擦除”按钮,因为那样会导致容易遭受灾难(一次由Microsoft制造的对话框在我身上发生),因为人们受过训练,只要他们想取消操作就可以单击第二个按钮。
因此,我需要的是,左(取消)按钮既成为默认按钮,又对Return,Esc和cmd-period键做出反应。
为了使其默认并响应Return键,我只需要将第一个按钮设置为keyEquivalent
空字符串,第二个按钮设置为“ \ r”。
但是当Esc或cmd-时,如何使警报取消。打字?
分配默认按钮,以通常的方式设置NSAlert。创建一个带有空边界的NSView新子类,并将其添加为NSAlert的附件视图。在子类中performKeyEquivalent
,检查Esc以及它是否匹配call[-NSApplication stopModalWithCode:]
或[-NSWindow endSheet:returnCode:]
。
#import "AppDelegate.h"
@interface AlertEscHandler : NSView
@end
@implementation AlertEscHandler
-(BOOL)performKeyEquivalent:(NSEvent *)event {
NSString *typed = event.charactersIgnoringModifiers;
NSEventModifierFlags mods = (event.modifierFlags & NSEventModifierFlagDeviceIndependentFlagsMask);
BOOL isCmdDown = (mods & NSEventModifierFlagCommand) != 0;
if ((mods == 0 && event.keyCode == 53) || (isCmdDown && [typed isEqualToString:@"."])) { // ESC key or cmd-.
[NSApp stopModalWithCode:1001]; // 1001 is the second button's response code
}
return [super performKeyEquivalent:event];
}
@end
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
[self alertTest];
[NSApp terminate:0];
}
- (void)alertTest {
NSAlert *alert = [NSAlert new];
alert.messageText = @"alert msg";
[alert addButtonWithTitle:@"OK"];
NSButton *cancelButton = [alert addButtonWithTitle:@"Cancel"];
alert.window.defaultButtonCell = cancelButton.cell;
alert.accessoryView = [AlertEscHandler new];
NSModalResponse choice = [alert runModal];
NSLog (@"User chose button %d", (int)choice);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句