目前我的应用程序界面上有一个允许打开文件的按钮,这是我的开放代码:
在我的app.h中:
- (IBAction)selectFile:(id)sender;
在我的app.m中:
@synthesize window;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
}
- (IBAction)selectFile:(id)sender {
NSOpenPanel *openPanel = [NSOpenPanel openPanel];
NSArray *fileTypes = [NSArray arrayWithObjects:@"xml",nil];
NSInteger result = [openPanel runModalForDirectory:NSHomeDirectory() file:nil types:fileTypes ];
if(result == NSOKButton){
NSString * input = [openPanel filename];
如何编辑我的代码以允许使用应用程序图标拖动&下降?
注意:我编辑了.plist文件并为“xml”添加了一行,但它改变了任何内容,当我的文件被放在图标上时出错。
注意2:我将“文件 - >打开...”链接到selectFile:这是指我的代码
注3:我的应用程序不是基于文档的应用程序
感谢您的帮助!
Miskia
答案 0 :(得分:15)
首先在.plist文件中添加适当的CFBundleDocumentTypes扩展名。
接下来实施以下代表:
- 应用程序:openFile :(丢失一个文件)
- 应用程序:openFiles :(删除多个文件)
参考:
NSApplicationDelegate Protocol Reference
对评论的回应:
一步一步的例子,希望它能让一切清楚:)
添加到.plist文件:
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>xml</string>
</array>
<key>CFBundleTypeIconFile</key>
<string>application.icns</string>
<key>CFBundleTypeMIMETypes</key>
<array>
<string>text/xml</string>
</array>
<key>CFBundleTypeName</key>
<string>XML File</string>
<key>CFBundleTypeRole</key>
<string>Viewer</string>
<key>LSIsAppleDefaultForType</key>
<true/>
</dict>
</array>
添加到... AppDelegate.h
- (BOOL)processFile:(NSString *)file;
- (IBAction)openFileManually:(id)sender;
添加到... AppDelegate.m
- (IBAction)openFileManually:(id)sender;
{
NSOpenPanel *openPanel = [NSOpenPanel openPanel];
NSArray *fileTypes = [NSArray arrayWithObjects:@"xml",nil];
NSInteger result = [openPanel runModalForDirectory:NSHomeDirectory() file:nil types:fileTypes ];
if(result == NSOKButton){
[self processFile:[openPanel filename]];
}
}
- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename
{
return [self processFile:filename];
}
- (BOOL)processFile:(NSString *)file
{
NSLog(@"The following file has been dropped or selected: %@",file);
// Process file here
return YES; // Return YES when file processed succesfull, else return NO.
}
答案 1 :(得分:0)