【问题标题】:What is the correct way for handling which button is pressed with NSAlert使用 NSAlert 处理按下哪个按钮的正确方法是什么
【发布时间】:2014-06-16 09:54:20
【问题描述】:

我在NSAlert 对象中添加了两个按钮,目前按钮一个的返回码是1001,而按钮默认为1000。我需要有效地确定在不使用幻数的情况下按下了给定警报中的哪个按钮。否则会变得一团糟。

-(void)showErrorMessage:(NSString*)errorMessage{
    NSAlert *alert = [[NSAlert alloc] init];
    [alert setMessageText:@"Error"];
    [alert setInformativeText:errorMessage];
    [alert setAlertStyle:NSCriticalAlertStyle];
    [alert addButtonWithTitle:@"Retake test"];
    [alert addButtonWithTitle:@"Cancel test"];
    [alert beginSheetModalForWindow:window modalDelegate:self didEndSelector:@selector(retakeFingerPrintAlert:returnCode:contextInfo:) contextInfo:nil];
}

- (void)retakeTestAlert:(NSAlert *)alert
                    returnCode:(int)returnCode
                   contextInfo:(void *)contextInfo{
    NSLog(@"clicked %d button\n", returnCode);


    //I want to determine very clearly which button is being pressed in the NSAlert
    //I dont want to work with magic numbers

    //And thus call the below method dependng on the button clicked
    [self onRetakeTest];
}

【问题讨论】:

    标签: objective-c macos cocoa-touch cocoa


    【解决方案1】:

    According to Apple's documentation on "addButtonWithTitle:", which you're using:

    前三个按钮的位置标识为 NSAlertFirstButtonReturn, NSAlertSecondButtonReturn, 返回码参数中的 NSAlertThirdButtonReturn 由 模态代表。后续按钮被标识为 NSAlertThirdButtonReturn +n,其中 n 为整数

    所以第一个按钮应该等于 [NSAlertFirstButtonReturn],即“1000”。第四个按钮应该是“1003”。

    到目前为止还有意义吗?

    【讨论】:

    • 我明白了。奇怪的是,第三个按钮的值是 1000,而左边的第一个按钮的值是 1002。这是从右到左索引按钮的标准吗?
    • 我猜它可能会有所不同,具体取决于您使用的语言/脚本。您的 UI 是否使用英语? :-)
    • 通常,在 OSX 下,“OK”在右下角,“Cancel”在左下角,所以这可能是订单的原因。
    • 大声笑,是的@michael,我是。
    猜你喜欢
    • 1970-01-01
    • 2021-05-15
    • 2017-04-24
    • 2015-03-08
    • 2012-07-25
    • 2018-05-10
    • 2014-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多