Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create and get return Value from Cocoa Dialog?

In my application, I want to create a dialog box with one text field, and a button, through which I can prompt user and get back user entered value.

How do I do this in Cocoa, Objective-C ?

I didn't find any predefined method for that.

like image 357
udr1990 Avatar asked Sep 12 '11 11:09

udr1990


3 Answers

You can call an NSAlert and put the NSTextField as it's accessoryView like this"

- (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;
    }
}
like image 138
0xSina Avatar answered Oct 26 '22 09:10

0xSina


IN 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) {

    }
like image 18
Kyle Browning Avatar answered Oct 26 '22 09:10

Kyle Browning


I believe what you are looking for is a sheet. Have a look at the Sheet Programming Topics documentation

I've just updated a Github Sample project on this. You can enter text in a field on the sheet and pass that back to the main window.

This example shows how to create a view in a nib and use a custom sheet controller class which uses a block as the callback, rather than having to create and pass in a selector.

like image 8
Abizern Avatar answered Oct 26 '22 11:10

Abizern