我有 NSSavePanel 和 accessoryView ,让用户选择图形格式,以便将图像(NSImage)保存为文件。到目前为止,我有以下内容。 (我正在跳过一些线来缩短它。)
- (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:@"..."];
}
我并非100%确定我做得对。我想要实现的是,只要用户在accessoryView的NSPopUpButton上选择文件格式,我就想将正确的扩展名附加到当前文件名。有这种神奇的方式吗?或者我是否必须以编程方式为我自己设置正确的扩展名为 setNameFieldStringValue 的当前文件名?
感谢您的帮助。
答案 0 :(得分:10)
我想要实现的是,每当用户在accessoryView的NSPopUpButton上选择文件格式时,我都希望将正确的扩展名附加到当前文件名。是否有一种神奇的方式呢?
是的,有。你不需要自己使用setNameFieldStringValue:
,让savePanel这样做。我们假设fileName
是一个完整的路径,如/Users/hg/Pictures/2013/08/Airplanes/pic123.png
,它存在一个带有matrix of radio buttons
的savePanel的accessoryView。每个按钮都有一个标题,如@“jpg”或@“png”或......矩阵的动作是-selectFileType:
- (IBAction) selectFileType:(id)sender
{
[savePanel setAllowedFileTypes:@[ [[sender selectedCell] title] ] ];
// this will set the right extension
}
为了使用savePanel,我尝试了以下代码:
- (void) saveImage:(NSImage *) theImg
{
savePanel = [NSSavePanel savePanel];
NSString *imageName = [fileName lastPathComponent];
NSString *suffix = [imageName pathExtension];
NSString *baseName = [imageName stringByDeletingPathExtension];
// prepare the savePanel
[savePanel setAccessoryView:accessoryView];
[savePanel setAllowedFileTypes:@[ suffix ] ];
[savePanel setDirectoryURL:[NSURL fileURLWithPath:fileName]]; // convert to URL
[savePanel setNameFieldStringValue:baseName ]; // without extension !
// savePanel does append the suffix
// and now start the savePanel and choose the wanted fileType
int rtn = [savePanel runModal]; // preferred method since 10.6
if( rtn==NSFileHandlingPanelCancelButton) return; // do nothing
// finally create and save the file
if( [[[savePanel allowedFileTypes] objectAtIndex:0] isEqualToString:@"jpg" ){
// save as jpg-file
}
// check for other fileTypes
. . .
}
答案 1 :(得分:2)
您必须使用setNameFieldStringValue
-(void)dropMenuChange:(NSPopUpButton *)sender {
NSSavePanel *savePanel = (NSSavePanel *)[sender window];
NSString *nameFieldString = [savePanel nameFieldStringValue];
NSString *nameFieldStringWithExt = [NSString stringWithFormat:@"%@.%@",[savePanel nameFieldStringValue], popupvalue];
[savePanel setNameFieldStringValue:nameFieldStringWithExt];
}