1

我有一个 NSAlert 表,里面有一个 NSComboBox。当用户按下 NSAlert 的按钮时,如何传递组合框值?
代码:

NSComboBox* comboBox = [[NSComboBox alloc] initWithFrame:NSMakeRect(0, 0, 150, 26)];
        [comboBox setTitleWithMnemonic:@"2"];

        for (int i=2; i<[array count]+1; i++){
            [comboBox addItemWithObjectValue:[NSString stringWithFormat:@"%i", i]];
        }

        [comboBox setEditable:NO];

        NSAlert *alert = [[NSAlert alloc] init];
        [alert addButtonWithTitle:@"Okay"];
        [alert addButtonWithTitle:@"Cancel"];
        [alert setMessageText:@"Choose a number"];
        [alert setAccessoryView:comboBox];
        [alert beginSheetModalForWindow:_window modalDelegate:self didEndSelector:@selector(alertToChooseX:returnCode:contextInfo:) contextInfo:nil];

- (void)alertToChooseX:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo {
    if (returnCode == NSAlertFirstButtonReturn) {
        NSLog(@"Pressed Okay");
    }
}
4

1 回答 1

0

在您的头文件中描述组合框,并在按下按钮“确定”后将其值设为:

.h

NSComboBox *comboBox;

_

comboBox = [[NSComboBox alloc] initWithFrame:NSMakeRect(0, 0, 150, 26)];
[comboBox setTitleWithMnemonic:@"2"];
.... // Your all code goes here


- (void)alertToChooseX:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo {
    if (returnCode == NSAlertFirstButtonReturn) {
        NSLog(@"Pressed Okay");

        NSLog(@"Selected ComboBox's String Value: %@", [comboBox stringValue]);
        NSLog(@"Selected ComboBox's Object Value: %@", [comboBox objectValueOfSelectedItem]);
        NSLog(@"Selected ComboBox's Item Index: %ld", [comboBox indexOfSelectedItem]);
    }
}

注意:不要忘记释放组合,因为它正在分配内存。

于 2012-05-24T21:22:58.340 回答