NSSavePanel by selecting part of the filename

How do I set part of the filename selected in NSSavePanel? I want the file name to be selected, not the file extension.

Here's what I noticed. If I set AllowedFileTypes: only the file name is selected for the save panel, not the file extension. However, if I don't install the allowed file types, then the file extension is added 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. It can be done?

+2


a source to share


2 answers


I understood that. 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 as the file name field is editable. The field editor is just an NSTextView and thus has a setSelectedRange: method. So I used this knowledge and here's the solution. Just call it on NSSavePanel anytime you only want to select the filename.



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

      

+2


a source


If you want the file name to be highlighted in the save panel, set

allowedFileTypes

include the default file type you specified in



nameFieldStringValue

You can also specify.

allowsOtherFileTypes = true;

0


a source







All Articles