Note that NSOpenPanel
inherits from NSSavePanel
, which in turn defines a delegate and a corresponding delegate protocol NSOpenSavePanelDelegate
. You can use the delegate to extend the behaviour of the open panel so as to include the restriction you’ve listed in your question.
For instance, assuming the application delegate implements the open panel restriction, make it conform to the NSOpenSavePanelDelegate
protocol:
@interface AppDelegate : NSObject <NSApplicationDelegate, NSOpenSavePanelDelegate>
@end
In the implementation of your application delegate, tell the open panel that the application delegate acts as the open panel delegate:
NSOpenPanel *openPanel = [NSOpenPanel openPanel];
[openPanel setDirectory:NSHomeDirectory()];
[openPanel setCanChooseDirectories:NO];
[openPanel setDelegate:self];
[openPanel runModal];
And implement the following delegate methods:
- (BOOL)panel:(id)sender shouldEnableURL:(NSURL *)url {
NSString *path = [url path];
NSString *homeDir = NSHomeDirectory();
return [path hasPrefix:homeDir] && ! [path isEqualToString:homeDir];
}
- (void)panel:(id)sender didChangeToDirectoryURL:(NSURL *)url {
NSString *path = [url path];
NSString *homeDir = NSHomeDirectory();
// If the user has changed to a non home directory, send him back home!
if (! [path hasPrefix:homeDir]) [sender setDirectory:homeDir];
}
- (BOOL)panel:(id)sender validateURL:(NSURL *)url error:(NSError **)outError {
NSString *path = [url path];
NSString *homeDir = NSHomeDirectory();
if (![path hasPrefix:homeDir]) {
if (outError)
*outError = ; // create an appropriate NSError instance
return NO;
}
return YES;
}