15

我正在尝试编写一个应用程序,允许用户将文件从 Finder 拖放到NSStatusItem. 到目前为止,我已经创建了一个实现拖放界面的自定义视图。当我将此视图添加为一个子视图时,NSWindow它一切正常 - 鼠标光标提供适当的反馈,并且当我的代码被删除时被执行。

但是,当我使用与视图相同的NSStatusItem's视图时,它的行为不正确。鼠标光标会给出适当的反馈,表明可以删除文件,但是当我删除文件时,我的删除代码永远不会被执行。

我需要做一些特别的事情来启用拖放NSStatusItem吗?

4

2 回答 2

30

我终于开始测试它并且它运行良好,所以你的代码肯定有问题。

这是一个允许拖动的自定义视图:

@implementation DragStatusView

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        //register for drags
        [self registerForDraggedTypes:[NSArray arrayWithObjects: NSFilenamesPboardType, nil]];
    }

    return self;
}

- (void)drawRect:(NSRect)dirtyRect
{
    //the status item will just be a yellow rectangle
    [[NSColor yellowColor] set];
    NSRectFill([self bounds]);
}

//we want to copy the files
- (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender
{
    return NSDragOperationCopy;
}

//perform the drag and log the files that are dropped
- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender 
{
    NSPasteboard *pboard;
    NSDragOperation sourceDragMask;

    sourceDragMask = [sender draggingSourceOperationMask];
    pboard = [sender draggingPasteboard];

    if ( [[pboard types] containsObject:NSFilenamesPboardType] ) {
        NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];

        NSLog(@"Files: %@",files);
    }
    return YES;
}


@end

以下是创建状态项的方法:

NSStatusItem* item = [[[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength] retain];

DragStatusView* dragView = [[DragStatusView alloc] initWithFrame:NSMakeRect(0, 0, 24, 24)];
[item setView:dragView];
[dragView release];
于 2011-06-27T13:03:35.217 回答
14

自优胜美地以来,不推荐使用设置视图的方法,但幸运的是,使用新属性 onNSStatusItem有更好的方法:NSStatusItemButtonNSStatusItem

- (void)applicationDidFinishLaunching: (NSNotification *)notification {
    NSImage *icon = [NSImage imageNamed:@"iconName"];
    //This is the only way to be compatible to all ~30 menu styles (e.g. dark mode) available in Yosemite
    [normalImage setTemplate:YES];
    statusItem.button.image = normalImage;

    // register with an array of types you'd like to accept
    [statusItem.button.window registerForDraggedTypes:@[NSFilenamesPboardType]];
    statusItem.button.window.delegate = self;

}

- (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender {
    return NSDragOperationCopy;
}

- (BOOL)performDragOperation:(id<NSDraggingInfo>)sender {
  //drag handling logic
}

请注意,该button属性仅从 10.10 开始可用,如果您支持 10.9 Mavericks 或更低版本,您可能必须保留旧解决方案。

于 2014-11-07T21:56:26.303 回答