带有绑定的 NSPopupButton 中的分隔项 [英] Separator item in NSPopupButton with bindings

查看:28
本文介绍了带有绑定的 NSPopupButton 中的分隔项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

NSPopupButton 的内容绑定到一个 NSArray 字符串.

The contents of a NSPopupButton are bound to an NSArray of strings.

我们如何通过绑定插入分隔符项目?

-"字符串(如在过去/经典时代)不起作用,即字面上显示为-"菜单项.

The "-" strings (like in the olden/Classic days) doesn't work, i.e. shows up literally as a "-" menu item.

是否有任何带有标准 Cocoa 类和绑定的开箱即用的解决方案?

这应该是一个微不足道的问题,但我找不到任何不涉及愚蠢黑客的问题的解决方案,例如子类化 NSMenuNSPopupButton 或其他非直观的解决方法.

This should be a trivial problem but I can't find any solution to the problem that doesn't involve silly hacks like subclassing NSMenu, NSPopupButton or other non-intuitive work arounds.

推荐答案

在使用绑定时,我找不到一种干净的方法来动态地向菜单添加分隔符.我发现的最简单(也是最可重用的)方法是使用 NSMenuDelegate 动态交换具有特定标题的 NSMenuItem,例如 @"---"menuNeedsUpdate 中的分隔项: 委托方法.

I couldn't find a clean way to dynamically add separators to a menu when using bindings. The easiest (and most reusable) way I've found is to use an NSMenuDelegate to dynamically swap out NSMenuItems with a specific title like @"---" with separator items in the menuNeedsUpdate: delegate method.

步骤 1:创建一个符合 NSMenuDelegate 协议的 NSObject

#import <Cocoa/Cocoa.h>

@interface SeparatorMenuDelegate : NSObject <NSMenuDelegate>
@end
@implementation SeparatorMenuDelegate

-(void)menuNeedsUpdate:(NSMenu *)menu {
    NSArray* fakeSeparators = [[menu itemArray] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"title == '---'"]];
    for (NSMenuItem* fakeSep in fakeSeparators) {
        [menu insertItem:[NSMenuItem separatorItem] atIndex:[menu indexOfItem:fakeSep]];
        [menu removeItem:fakeSep];
    }
}

@end

第 2 步:在 Interface Builder 中进行链接.

将一个对象拖到包含 NSPopupButton 实例的场景中.

Drag out an Object into the scene that contains the NSPopupButton instance.

设置对象的类为SeparatorMenuDelegate

旋转打开文档大纲中的 NSPopupButton 控件并选择其中的菜单.然后将 Menu 的委托设置为您之前拖入的 SeparatorMenuDelegate 对象.

Twirl open the NSPopupButton control in the Document Outline and select the Menu inside it. Then set the delegate for the Menu to the SeparatorMenuDelegate object that you dragged in earlier.

此后,菜单中标题为@---"的所有项目都将转换为分隔符项目.

After this, all items in the menu with a title of @"---" will be converted to separator items.

如果你在同一个场景中有多个 NSPopupButton 实例,你可以将它们的 Menu 的代理设置为同一个对象(每个场景只需要一个 SeparatorMenuDelegate).

If you have multiple NSPopupButton instances in the same scene, you can set the delegate of their Menu to the same object (you only need one SeparatorMenuDelegate per scene).

这篇关于带有绑定的 NSPopupButton 中的分隔项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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