【问题标题】:Passing NSComboBox value that is inside a NSAlert Sheet传递 NSAlert Sheet 中的 NSComboBox 值
【发布时间】:2012-05-24 20:50:23
【问题描述】:

我有一个 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");
    }
}

【问题讨论】:

    标签: objective-c macos cocoa combobox nsalert


    【解决方案1】:

    在您的头文件中描述 comboBox 并在按下按钮“Okay”后将其值设为:

    .h

    NSComboBox *comboBox;
    

    .m

    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]);
        }
    }
    

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

    【讨论】:

    • 我正在考虑做类似的事情,但我认为有一种方法可以通过 NSAlert 传递值。谢谢你!顺便说一句,我使用的是 ARC,所以没有发布:P
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-08
    • 2020-11-02
    • 1970-01-01
    • 2010-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多