Question

How do I set the part of the file name that is selected in NSSavePanel? I only want the file name selected and not the file extension.

Here's what I noticed. If I setAllowedFileTypes: for the save panel then only the file name is selected but not the file extension. However if I don't set the allowed file types then the file extension is selected along with the file name.

I don't want to use setAllowedFileTypes but I still want to control the selection so that the file extension is not selected. Can that be done?

Was it helpful?

Solution

I figured it out. I didn't know this before but every window has a field editor if some object containing text is being edited. As such a save panel has one because the file name field is being edited. A field editor is just an NSTextView and thus has a method setSelectedRange:. So I used this knowledge and here's the solution. Just call this on the NSSavePanel any time you want to select just the file name.

NSText* editor = [savePanel fieldEditor:NO forObject:nil];
if (editor) {
    NSString* nameFieldString = [savePanel nameFieldStringValue];
    NSString* nameFieldExt = [nameFieldString pathExtension];
    if (nameFieldExt != nil) {
        NSInteger newLength = [nameFieldString length]-[nameFieldExt length]-1;
        [editor setSelectedRange:NSMakeRange(0, newLength)];
    }
}

OTHER TIPS

If you just want the save panel to highlight the filename, set

allowedFileTypes

to include default filetype you specified in

nameFieldStringValue

You may also want to specify.

allowsOtherFileTypes = true;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top