Search code examples
objective-cmacoscocoaosx-mountain-lion

NSSavePanel Changing File Name Extensions With AccessoryView


I have NSSavePanel with accessoryView to let the user select a graphic format so that they can save an image (NSImage) as a file. So far, I have the following. (I'm skipping some lines to make it short.)

- (void)exportFile {    
    NSString *filename;
    if (formatIndex1 == 0) { // Default selection by user in Preferences
        filename = @"Untitled.bmp";
    }
    else if (formatIndex1 == 1) {
        filename = @"Untitled.gif";
    }
    ...

    [panel setAllowedFileTypes:[[NSArray alloc] initWithObjects:@"bmp",@"gif",@"jpg",@"jp2",@"png",nil]];
    [panel setAllowsOtherFileTypes:NO];
    [panel setExtensionHidden:NO];
    [panel setCanCreateDirectories:YES];
    [panel setNameFieldStringValue:filename];
    [panel setAccessoryView:accessoryView1];
    [formatMenu1 setAction:@selector(dropMenuChange:)]; // formatMenu1 is NSPopUpButton
    [formatMenu1 setTarget:self];

    [panel beginSheetModalForWindow:window completionHandler:^(NSInteger result) {
        if (result == NSFileHandlingPanelOKButton) {
            // getting panel url
        }
    }];
}

-(void)dropMenuChange:(NSPopUpButton *)sender { 
    NSSavePanel *savePanel = (NSSavePanel *)[sender window];
    [savePanel setNameFieldStringValue:@"..."];
}

I'm not 100% sure that I'm doing it right. What I want to achieve is that I want to append the right extension to the current file name whenever the user selects a file format on accessoryView's NSPopUpButton. Is there a magical way of doing that? Or do I have to set the current file name with the right extension to setNameFieldStringValue programmatically for myself?

Thank you for your help.


Solution

  • You have to set current file name with the right extension using setNameFieldStringValue

    -(void)dropMenuChange:(NSPopUpButton *)sender { 
        NSSavePanel *savePanel = (NSSavePanel *)[sender window];
        NSString *nameFieldString = [savePanel nameFieldStringValue];
        NSString *nameFieldStringWithExt = [NSString stringWithFormat:@"%@.%@",[savePanel nameFieldStringValue], popupvalue];
        [savePanel setNameFieldStringValue:nameFieldStringWithExt];
    }