0

アプリケーションに単純なドラッグ アンド ドロップを実装したいと考えています。ファイルをウィンドウにドラッグすると、NSLog でファイルパスを返したいと思います。これが私のコードですが、ファイルをドラッグしても何も起こりません。ちなみに、私はAppDelegateをwindow(delegate)でアウトレットを参照して接続し、windowからすべてを受け取るようにしました。

AppDelegate.m :

#import "AppDelegate.h"

@implementation AppDelegate

@synthesize window = _window;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
      [_window registerForDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType, nil]]; 
}

-(NSDragOperation)draggingEntered:(id < NSDraggingInfo >)sender
{
    return NSDragOperationGeneric;
}
-(BOOL)prepareForDragOperation:(id < NSDraggingInfo >)sender
{
    NSPasteboard* pbrd = [sender draggingPasteboard];
    NSArray *draggedFilePaths = [pbrd propertyListForType:NSFilenamesPboardType];
    // Do something here.
    return YES;

   NSLog(@"string2 is %@",draggedFilePaths);}

@end

AppDelegate.h:

//
//  AppDelegate.h
//  testdrag
//
//  Created by admin on 18.07.12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import <Cocoa/Cocoa.h>

@interface AppDelegate : NSObject <NSApplicationDelegate>


@property (assign) IBOutlet NSWindow *window;

@end
4

2 に答える 2

2

画面スペースを占有するオブジェクト (ウィンドウまたはビュー) のみが、ドラッグ イベントを受け入れて処理できます。あなたのアプリデリゲートはそれらのどちらでもありません。さらに、ウィンドウは受信したメッセージをデリゲートに送信しません。NSWindowDelegateプロトコルの一部であるメッセージのみを送信します。このドラッグ コードをビュー クラスに実装する必要があり、そのインスタンスが画面に表示されます。

于 2012-07-18T19:53:41.860 に答える
2

これは古い質問ですが、この問題を解決した方法は次のとおりです。

のサブクラスを作成しNSWindow、 という名前を付けましたMainWindow。次に、プロトコルNSDraggingDestinationを新しいクラスに追加しましたMainWindow。Interface Builder でアプリケーション ウィンドウを選択MainWindowし、Identity Inspector にクラス名を入力しました。

AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    [_window registerForDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType, nil]];
}

そしての実装MainWindow

#import "MainWindow.h"

@implementation MainWindow

- (void)awakeFromNib {
    [super awakeFromNib];
    printf("Awake\n");
}

- (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender {
    printf("Enter\n");
    return NSDragOperationEvery;
}

/*
- (NSDragOperation)draggingUpdated:(id<NSDraggingInfo>)sender {
    return NSDragOperationEvery;
}
*/

- (void)draggingExited:(id<NSDraggingInfo>)sender {
    printf("Exit\n");
}

- (BOOL)prepareForDragOperation:(id<NSDraggingInfo>)sender {
    printf("Prepare\n");
    return YES;
}

- (BOOL)performDragOperation:(id<NSDraggingInfo>)sender {
    printf("Perform\n");

    NSPasteboard *pboard = [sender draggingPasteboard];

    if ( [[pboard types] containsObject:NSFilenamesPboardType] ) {
        NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
        unsigned long numberOfFiles = [files count];
        printf("%lu\n", numberOfFiles);
    }
    return YES;
}

- (void)concludeDragOperation:(id<NSDraggingInfo>)sender {
    printf("Conclude\n");
}

@end

魔法のように動作します!(ついに!)

于 2015-08-02T23:55:57.717 に答える