问题描述
我创建了一个简单的 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子类中按照这个问题的代码实现了高亮显示:
#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:
这篇关于使用自定义视图突出显示NSMenuItem?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!