Frage

I am having some troubles understanding how to wire a custom NSView for an NSMenuItem to support both animation and dragging and dropping. I have the following subclass of NSView handling the bulk of the job. It draws my icon when the application launches correctly, but I have been unable to correctly setup the subview to change when I invoke the setIcon function from another caller. Is there some element of the design that I am missing?

TrayIconView.m

#import "TrayIconView.h"

@implementation TrayIconView
@synthesize statusItem;
static NSImageView *_imageView;

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
      statusItem = nil;
      isMenuVisible = NO;
      _imageView = [[NSImageView alloc] initWithFrame:[self bounds]];
      [self addSubview:_imageView];
    }

    return self;
}

- (void)drawRect:(NSRect)dirtyRect
{
  // Draw status bar background, highlighted if menu is showing
  [statusItem drawStatusBarBackgroundInRect:[self bounds]
                              withHighlight:isMenuVisible];
}

- (void)mouseDown:(NSEvent *)event {
  [[self menu] setDelegate:self];
  [statusItem popUpStatusItemMenu:[self menu]];
  [self setNeedsDisplay:YES];
}

- (void)rightMouseDown:(NSEvent *)event {
  // Treat right-click just like left-click
  [self mouseDown:event];
}

- (void)menuWillOpen:(NSMenu *)menu {
  isMenuVisible = YES;
  [self setNeedsDisplay:YES];
}

- (void)menuDidClose:(NSMenu *)menu {
  isMenuVisible = NO;
  [menu setDelegate:nil];
  [self setNeedsDisplay:YES];
}

- (void)setIcon:(NSImage *)icon {
  [_imageView setImage:icon];
}

TrayIconView.h

#import <Cocoa/Cocoa.h>

@interface TrayIconView : NSView

{
  BOOL isMenuVisible;
}

@property (retain, nonatomic) NSStatusItem *statusItem;

- (void)setIcon:(NSImage *)icon;

@end
War es hilfreich?

Lösung

The solution to this problem was actually outside of the view detailed here. The caller of the interface was being double instantiated on accident, thus nulling out the reference to the previously created NSView. After correcting that concern the app draws and works just fine.

With regard to dragging, I just implemented a subclass of NSView that implemented the Cocoa draggable protocol and added it as a subview to this parent class. That allows dragging onto the currently established NSRect that contains the menubar icon.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top