How to create and get return Value from Cocoa Dialog?

前端 未结 4 1109
抹茶落季
抹茶落季 2020-12-13 15:46

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

4条回答
  •  生来不讨喜
    2020-12-13 16:29

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

提交回复
热议问题