首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用NSStatusItem进行拖放

使用NSStatusItem进行拖放
EN

Stack Overflow用户
提问于 2011-04-14 21:19:37
回答 2查看 4.6K关注 0票数 15

我正在尝试编写一个应用程序,允许用户从查找器中拖动文件并将它们放到NSStatusItem上。到目前为止,我已经创建了一个实现拖放界面的自定义视图。当我将这个视图添加为NSWindow的子视图时,一切都正常工作--鼠标光标给出适当的反馈,并且当我的代码被拖放时,我的代码将被执行。

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

是否需要执行一些特殊操作才能使用NSStatusItem进行拖放

EN

回答 2

Stack Overflow用户

发布于 2011-06-27 21:03:35

我终于抽出时间来测试它,它工作得很好,所以肯定是你的代码出了问题。

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

代码语言:javascript
复制
@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

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

代码语言:javascript
复制
NSStatusItem* item = [[[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength] retain];

DragStatusView* dragView = [[DragStatusView alloc] initWithFrame:NSMakeRect(0, 0, 24, 24)];
[item setView:dragView];
[dragView release];
票数 30
EN

Stack Overflow用户

发布于 2014-11-08 05:56:26

自Yosemite以来,不推荐使用在NSStatusItem上设置视图的方法,但幸运的是,有一种更好的方法使用NSStatusItem上的新NSStatusItemButton属性

代码语言:javascript
复制
- (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;

}

代码语言:javascript
复制
- (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender {
    return NSDragOperationCopy;
}

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

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

票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5663887

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档