2011-09-12 52 views
15

在我的應用程序中,我想創建一個對話框,其中包含一個文本字段和一個按鈕,通過它我可以提示用戶並獲取用戶輸入的值。如何從Cocoa對話框創建並獲取返回值?

我該如何在Cocoa,Objective-C中做到這一點?

我沒有找到任何預定義的方法。

+2

沒有爲一個預定義的方法,因爲這是很糟糕的用戶界面。這應該只是一個領域。 –

回答

40

可以調用NSAlert,把的NSTextField,因爲它是accessoryView的這樣的」

- (NSString *)input: (NSString *)prompt defaultValue: (NSString *)defaultValue { 
    NSAlert *alert = [NSAlert alertWithMessageText: prompt 
            defaultButton:@"OK" 
            alternateButton:@"Cancel" 
             otherButton:nil 
         informativeTextWithFormat:@""]; 

    NSTextField *input = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 200, 24)]; 
    [input setStringValue:defaultValue]; 
    [input autorelease]; 
    [alert setAccessoryView:input]; 
    NSInteger button = [alert runModal]; 
    if (button == NSAlertDefaultReturn) { 
     [input validateEditing]; 
     return [input stringValue]; 
    } else if (button == NSAlertAlternateReturn) { 
     return nil; 
    } else { 
     NSAssert1(NO, @"Invalid input dialog button %d", button); 
     return nil; 
    } 
} 
+0

如果您正在通過alloc-init創建它,請不要忘記釋放NSTextField。 –

+0

@SebastianHojas他們是否仍然需要這樣做,如果他們使用ARC進行內存管理? – rd108

+0

@ rd108使用ARC時不需要/不允許發佈。 –

7

我相信你正在尋找的是一個表。有一個看看Sheet Programming Topics文檔

我我們剛剛更新了Github Sample這個項目,你可以在表單中的一個字段中輸入文本,並將其傳遞迴主窗口。

這個例子展示瞭如何在一個nib中創建一個視圖並使用一個自定義圖紙控制器類whic h使用塊作爲回調,而不必創建並傳入選擇器。

14

在Mac OS X 10.10:

NSAlert *alert = [[NSAlert alloc] init]; 
    [alert setMessageText:@"Permission denied, sudo password?"]; 
    [alert addButtonWithTitle:@"Ok"]; 
    [alert addButtonWithTitle:@"Cancel"]; 

    NSTextField *input = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 200, 24)]; 
    [input setStringValue:@""]; 

    [alert setAccessoryView:input]; 
    NSInteger button = [alert runModal]; 
    if (button == NSAlertFirstButtonReturn) { 
     password = [input stringValue]; 
    } else if (button == NSAlertSecondButtonReturn) { 

    } 
4

爲Xcode的7.2.1 OS X 10.11,並在斯威夫特的一個例子:

let a = NSAlert() 
a.messageText = "Please enter a value" 
a.addButtonWithTitle("Save") 
a.addButtonWithTitle("Cancel") 

let inputTextField = NSTextField(frame: NSRect(x: 0, y: 0, width: 300, height: 24)) 
inputTextField.placeholderString = "Enter string" 
a.accessoryView = inputTextField 

a.beginSheetModalForWindow(self.window!, completionHandler: { (modalResponse) -> Void in 
    if modalResponse == NSAlertFirstButtonReturn { 
     let enteredString = inputTextField.stringValue 
     print("Entered string = \"\(enteredString)\"") 
    } 
}) 
相關問題