使用自定义视图突出显示NSMenuItem? [英] Highlighting a NSMenuItem with a custom view?

查看:871
本文介绍了使用自定义视图突出显示NSMenuItem?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的 NSStatusBar ,并将 NSMenu 设置为菜单。我还添加了一些 NSMenuItems 到这个菜单,它工作正常(包括选择器和突出显示),但一旦我添加自定义视图(setView :)不突出发生。

  CustomMenuItem * menuItem = [[CustomMenuItem alloc] initWithTitle:@action:@selector(openPreferences :) keyEquivalent:@ ]; 
[menuItem foo];
[menuItem setTarget:self];
[statusMenu insertItem:menuItem atIndex:0];
[menuItem release];

我的foo方法是:

   - (void)foo {
NSView * view = [[NSView alloc] initWithFrame:CGRectMake(5,10,100,20)
[self setView:view];
}



如果我删除了setView方法,它会突出显示。



我已经搜索和搜索,找不到实现/启用此方法的方法。



编辑 / p>

我在NSView子类中按照这个问题的代码实现了高亮显示:



NSMenuItem的视图(NSView子类的实例)不突出显示悬停

  #define menuItem([self enclosingMenuItem])

- )drawRect:(NSRect)rect {
BOOL isHighlighted = [menuItem isHighlighted];
if(isHighlighted){
[[NSColor selectedMenuItemColor] set];
[NSBezierPath fillRect:rect];
} else {
[super drawRect:rect];
}
}


解决方案

您要向菜单项添加视图,该视图必须绘制突出显示本身。你不能免费得到,恐怕。从菜单编程主题


具有视图的菜单项不会绘制其标题,状态,字体或其他标准绘图属性,并将绘图责任完全分配给视图。



I have created a simple NSStatusBar with a NSMenu set as the menu. I have also added a few NSMenuItems to this menu, which work fine (including selectors and highlighting) but as soon as I add a custom view (setView:) no highlighting occurs.

CustomMenuItem *menuItem = [[CustomMenuItem alloc] initWithTitle:@"" action:@selector(openPreferences:) keyEquivalent:@""];
[menuItem foo];
[menuItem setTarget:self];
[statusMenu insertItem:menuItem atIndex:0];
[menuItem release];

And my foo method is:

- (void)foo {
  NSView *view = [[NSView alloc] initWithFrame:CGRectMake(5, 10, 100, 20)];
  [self setView:view];
}

If I remove the setView method, it will highlight.

I have searched and searched and cannot find a way of implementing/enabling this.

Edit

I implemented highlight by following the code in this question in my NSView SubClass:

An NSMenuItem's view (instance of an NSView subclass) isn't highlighting on hover

#define menuItem ([self enclosingMenuItem])

- (void) drawRect: (NSRect) rect {
    BOOL isHighlighted = [menuItem isHighlighted];
    if (isHighlighted) {
        [[NSColor selectedMenuItemColor] set];
        [NSBezierPath fillRect:rect];
    } else {
        [super drawRect: rect];
    }
}

解决方案

If you're adding a view to a menu item, that view has to draw the highlight itself. You don't get that for free, I'm afraid. From the Menu Programming Topics:

A menu item with a view does not draw its title, state, font, or other standard drawing attributes, and assigns drawing responsibility entirely to the view.

这篇关于使用自定义视图突出显示NSMenuItem?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆