Drag and Drop with NSStatusItem

后端 未结 2 1498
梦毁少年i
梦毁少年i 2020-12-07 15:58

I\'m trying to write an application that allows the user to drag files from the Finder and drop them onto an NSStatusItem. So far, I\'ve created a custom view

2条回答
  •  萌比男神i
    2020-12-07 16:46

    I finally got around to testing this and it works perfectly, so there's definitely something wrong with your code.

    Here's a custom view that allows dragging:

    @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)sender
    {
        return NSDragOperationCopy;
    }
    
    //perform the drag and log the files that are dropped
    - (BOOL)performDragOperation:(id )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
    

    Here's how you'd create the status item:

    NSStatusItem* item = [[[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength] retain];
    
    DragStatusView* dragView = [[DragStatusView alloc] initWithFrame:NSMakeRect(0, 0, 24, 24)];
    [item setView:dragView];
    [dragView release];
    

提交回复
热议问题