7

現在、アプリのインターフェイスにファイルを開くことができるボタンがあります。ここに私のオープンコードがあります:

私の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: "File -> Open..." を selectFile にリンクしました: 私のコードを参照して
ください 注 3: 私のアプリはドキュメントベースのアプリケーションではありません


ご協力いただきありがとうございます!
ミスキア

4

2 に答える 2

16

まず、.plist ファイル内の CFBundleDocumentTypes に適切な拡張子を追加します。

次に、次のデリゲートを実装します。
- application:openFile: (1 つのファイルがドロップされます)
- application:openFiles: (複数のファイルがドロップされます)

参照:
NSApplicationDelegate プロトコル リファレンス

コメントへの返信:

ステップごとの例です。うまくいけば、すべてが明確になります:)

.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.
}
于 2011-03-16T21:15:48.503 に答える
0

クイック&ダーティなソリューションの場合:

Cocoa: 任意のファイル タイプをドラッグ アンド ドロップ

Xcode バージョン 11.4 (11E146) カタリナ 10.15.4 (19E266) でテスト済み

于 2020-04-01T10:17:02.793 に答える