具有自定义视图的NSMenuItem不会更新

时间:2012-03-09 16:07:41

标签: objective-c macos cocoa nsmenuitem nsviewcontroller

我有一个带有自定义视图的NSMenuItem。但是,当我想更新菜单中的第一行时,它会将内容添加到xib文件中,而不是像我设置的那样。

我的代码: AppDelegate.m:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    _helper = [[Helper alloc] init];

    statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength];
    [statusItem setMenu:self.statusMenu];
    [statusItem setTitle:@"GravAccount"];
    [statusItem setHighlightMode:YES];

    _gravatarLoader = [[GravatarLoader alloc] initWithTarget:self andHandle:@selector(setGravatarImage:)];

    // Get email address
    _email = [_helper getEmailAddress];

    if (_email != nil)
    {
        [_gravatarLoader loadEmail:_email withSize:50.0];
    }
}

- (void)setGravatarImage:(NSImage*)image
{
    NSLog(@"Image loaded!");

    GravatarMenuItem *menuItem = [[GravatarMenuItem alloc] initWithNibName:@"GravatarMenuItem" bundle:nil];
    [menuItem.label setTitle:_email];
    [menuItem.imageView setImage:image];

    NSLog(@"Email: %@", _email);

    NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
    [item setView:menuItem.view];

    [self.statusMenu removeItemAtIndex:0];
    [self.statusMenu insertItem:item atIndex:0];
}

GravatarMenuItem.h:

#import <Cocoa/Cocoa.h>

@interface GravatarMenuItem : NSViewController

@property (nonatomic, strong) IBOutlet NSImageView *imageView;
@property (nonatomic, strong) IBOutlet NSTextFieldCell *label;

@end

出口链接在文件所有者的XIB文件中。

这是结果: 经度:

2012-03-09 16:57:24.314 appName[51158:403] Image loaded!
2012-03-09 16:57:24.316 appName[51158:403] Email: Paul@******.se

结果:
Result

1 个答案:

答案 0 :(得分:5)

当你这样做时:

GravatarMenuItem *menuItem = [[GravatarMenuItem alloc] initWithNibName:@"GravatarMenuItem" bundle:nil];

它只创建视图控制器。它实际上并没有从笔尖加载视图。当您访问属性时,它们很可能是nil,因为视图尚未加载(并且尚未建立连接)。

如果您将代码更新为以下内容,则一切正常:

GravatarMenuItem *menuItem = [[GravatarMenuItem alloc] initWithNibName:@"GravatarMenuItem" bundle:nil];
[menuItem view]; // load the view from the nib
[menuItem.label setTitle:_email];
[menuItem.imageView setImage:image];