2012-05-24 37 views
1

我有一個NSAlert表,裏面有一個NSComboBox。如何在用戶按下NSAlert按鈕時傳遞組合框值?
代碼:傳遞NSAlert表內的NSComboBox值

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

回答

0

描述組合框在你的頭文件後按下按鈕 「」 走是這樣的值:

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

注:不要忘記釋放組合框因爲它分配內存。

+0

我在想做這樣的事情,但我認爲有一種方法可以將值傳遞給NSAlert。謝謝!順便說一句,我使用ARC所以沒有發佈:P –

+0

@PedroVieira歡迎您:) –