简单拖放到窗口返回文件路径

时间:2012-07-18 19:33:21

标签: objective-c cocoa xcode4.3

我想在我的应用程序中实现简单的拖放操作。 如果您将文件拖到窗口我想要返回 NSLog的文件路径。这是我的代码但是 如果我拖动文件没有任何反应。顺便说一句我 将AppDelegate连接到引用插座 用窗口(委托)从窗口接收所有东西。

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

2 个答案:

答案 0 :(得分:2)

只有占据屏幕空间的对象 - 窗口或视图 - 才能接受和处理拖动事件。您的应用代表既不是那些。此外,窗口不会将其收到的任何消息发送给其委托。它仅发送属于NSWindowDelegate协议的消息。您需要在视图类中实现此拖动代码,其实例将显示在屏幕上。

答案 1 :(得分: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

像魅力一样! (最后!)