单击后从 NSMenuItem 中删除突出显示吗?
我已经向 NSMenuItem 的子类(位于 NSStatusMenu 中)添加了一个自定义视图,这意味着默认情况下它不会以蓝色/灰色背景“突出显示”。
我通过使用以下代码实现了这一点:
- (void)drawRect:(NSRect)rect {
BOOL isHighlighted = [menuItem isHighlighted];
if (isHighlighted) {
[[NSColor selectedMenuItemColor] set];
[NSBezierPath fillRect:rect];
[menuItem addHover];
} else {
[super drawRect:rect];
[menuItem removeHover];
}
}
- (void)mouseUp:(NSEvent*)event {
NSMenuItem *item = [self enclosingMenuItem];
NSMenu *menu = [item menu];
[menu cancelTracking];
[menu performActionForItemAtIndex:[menu indexOfItem:item]];
}
菜单项很好地突出显示,我还可以单击每个项目;但是,当我单击它们时,一旦我重新打开菜单,它们似乎就会保持 isHighlighted 状态。
有没有办法更改它,以便当我单击时,下次打开菜单时突出显示的状态会被删除?
I have added a custom view to my subclass of NSMenuItem (which sits in a NSStatusMenu), which means that by default it will not get "highlighted" with a blue/gray background.
I implemented this by using the following code:
- (void)drawRect:(NSRect)rect {
BOOL isHighlighted = [menuItem isHighlighted];
if (isHighlighted) {
[[NSColor selectedMenuItemColor] set];
[NSBezierPath fillRect:rect];
[menuItem addHover];
} else {
[super drawRect:rect];
[menuItem removeHover];
}
}
- (void)mouseUp:(NSEvent*)event {
NSMenuItem *item = [self enclosingMenuItem];
NSMenu *menu = [item menu];
[menu cancelTracking];
[menu performActionForItemAtIndex:[menu indexOfItem:item]];
}
The menu items get highlighted fine, and I can also click on each item; however when I do click on them, they seem to keep the isHighlighted state once I reopen the menu.
Is there a way of changing it so when I click, the highlighted state gets removed when I next open the menu?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
令我震惊的是,我们必须这样做,而不是简单的 NSMenuItem setHighlighted 或 NSMenu removeHighlights 或其他东西。这是一个看起来很像 MrWalker 的答案的片段。它只是从菜单中删除您自己的菜单项并将其放回去。
Blows my mind that we have to do this instead of a simple NSMenuItem setHighlighted, or NSMenu removeHighlights, or something. Here's a snippet that looks a lot like MrWalker's answer.. It just removes your own menu item from the menu and puts it right back.
我通过删除自定义视图中的 mouseUp 方法来修复此问题,然后在其中添加另一个“隐藏” NSView,它具有以下方法:
I fixed this by removing the mouseUp method in my custom view, and then adding another "hidden" NSView inside it which has the following method:
我的解决方案是在cancelTracking之后删除并重新添加菜单项:
My solution was to remove and re-add the menu items after cancelTracking:
我在应用程序的主菜单中遇到了一个独特的情况,删除和重新添加菜单项并没有删除菜单项的突出显示。这是我用来删除突出显示的 Swift 函数,方法是添加一个虚拟菜单项,“单击”它,然后删除虚拟项目:
I had a unique situation with the application's main menu, where removing and re-adding the menu items didn't remove the highlight of the menu item. Here's the Swift function I used to remove the highlight by adding a dummy menu item, "clicking" it, then removing the dummy item: