objective-c - 带有实时字体(样式文本)的 NSPopupButton

标签 objective-c macos cocoa osx-mountain-lion nspopupbutton

我想知道是否可以在弹出按钮控件(NSPopupButton)中显示实时字体?目前,我通过以下方式加载一个带有可用字体列表的弹出按钮。

NSArray *familyNames = [[NSFontManager sharedFontManager] availableFontFamilies];
NSMutableArray *fontarray = [[NSMutableArray alloc] initWithObjects:nil];
[fontarray addObject:@"- Select one - "];
for (NSString *family in familyNames) {
    [fontarray addObject:family];
}
[fontmenu1p addItemsWithTitles:fontarray];

也许,像下面这样,使用 NSMutableAttributedString?

for (NSString *family in familyNames) {
    NSDictionary *attr1 = [NSDictionary dictionaryWithObjectsAndKeys:[NSFont fontWithName:family size:[NSFont systemFontSize]],NSFontAttributeName,[NSColor blackColor],NSForegroundColorAttributeName,nil];
    NSMutableAttributedString *aString = [[NSMutableAttributedString alloc] initWithString:family];
    [aString setAttributes:attr1 range:NSMakeRange(0,family.length-1)];
    [fontarray addObject:aString];
}
[fontmenu1p addItemsWithTitles:fontarray];

我收到越界错误。我不知道我的做法是否正确。我什至不知道 popupbutton 控件是否支持样式文本。

感谢您的帮助。

最佳答案

即使我没有测试过,我认为我们的方法也行不通。 NSPopUpButton 的菜单有一个方便的 API。方便,但时间短。 (通常弹出项目没有属性,没有单独的 View 等等。)

我会尝试构建 NSMenuItem 的实例对于每个项目。有一个二传手-setAttributedTitle: ,它允许您设置属性字符串。然后您必须将其聚合到 NSMenu 的实例和 set the menu到弹出按钮。

顺便说一句:[aString setAttributes:attr1 range:NSMakeRange(0,family.length-1)]; 为什么-1?长度是长度,而不是最后一个字符的索引。并且您想要设置一个范围,该范围也采用长度,而不是最后一个字符的索引。

关于objective-c - 带有实时字体(样式文本)的 NSPopupButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17247917/

相关文章:

macos - 使用 AppleScript 拆分全屏应用程序

javascript - 在 Safari JavaScript 中捕捉 ⌘+1

cocoa - “NSTextView”没有名为 'setString' 的成员

ios - AVPlayer - 播放时切换流质量

objective-c - TableView 单元格在修饰时不会失去高亮显示

ios - 尽管有 `if let` 构造,编译器告诉我解包变量

swift - 在 Swift 2 中断开当前的互联网连接

objective-c - 检查从 NSURLConnection 填充的自定义对象的 NSMutableArray 内是否完成

iPhone 4s 6.1.2 版 UIViewcontroller 在使用相机拍照时刷新

cocoa - 如何制作滚动点动画?