NSPopupButton中的分隔符项目与绑定 [英] Separator item in NSPopupButton with bindings

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

问题描述

NSPopupButton 的内容绑定到字符串的 NSArray

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

如何通过绑定插入分隔符?

How can we insert a separator item via bindings?

c $ c> - 字符串(例如在olden / classic天)不工作,即字面上显示为 - 菜单项。

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

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

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

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动态交换NSMenuItems具有特定的标题,如 @--- 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协议

#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

strong>第2步:在Interface Builder中链接内容。

Step 2: Link things up in Interface Builder.

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

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

设置对象的class to SeparatorMenuDelegate

Set the object's class to SeparatorMenuDelegate

旋转打开文档大纲中的NSPopupButton控件,并选择其中的菜单。然后将菜单的委托设置为之前拖动的 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实例,您可以将其菜单的委托设置为同一个对象(您只需要一个 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天全站免登陆