如何设置NSPopupButton菜单项的颜色?
zsohkypk1#
在网上搜索,我只找到了a really hacked, contorted answer to this question,可以更优雅地回答如下:
NSArray *itemArray = [scalePopup itemArray]; int i; NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys: [NSColor redColor], NSForegroundColorAttributeName, [NSFont systemFontOfSize: [NSFont systemFontSize]], NSFontAttributeName, nil]; for (i = 0; i < [itemArray count]; i++) { NSMenuItem *item = [itemArray objectAtIndex:i]; NSAttributedString *as = [[NSAttributedString alloc] initWithString:[item title] attributes:attributes]; [item setAttributedTitle:as]; }
flmtquvp2#
我也有同样的问题。为了保留原始文本属性,我的解决方案如下:
NSRange range = NSMakeRange(0, 0); NSAttributedString *cellStr = [[self.popup cell] attributedTitle]; NSMutableDictionary *cellAttr = [[cellStr attributesAtIndex:range.location effectiveRange:&range] mutableCopy]; [cellAttr setObject:[NSColor redColor] forKey:NSForegroundColorAttributeName]; NSArray *menuItems = [self.popup itemArray]; for (NSMenuItem *menu in menuItems ) { NSString *orgTitle = [menu title]; NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:orgTitle attributes:cellAttr]; [menuItem setAttributedTitle:title]; }
jhdbpxl93#
Swift 5.5
为菜单项分配属性字符串。例如,如果以前选择了该菜单项,则通过分配粗体绿色属性字符串来更改标题颜色。我有一个属性,我为以前选择的标题,所以我可以很容易地删除属性字符串,如果另一个标题被选中。
var previousTitle: String = ""
然后在我的方法中,我做以下事情
if !previousTitle.isEmpty { // Remove the previously assigned attributed title myPopUpButton.selectItem(withTitle: previousTitle) myPopUpButton.selectedItem?.attributedTitle = nil } previousTitle = <some previously selected title> myPopUpButton.selectItem(withTitle: previousTitle) let font = NSFont.systemFont(ofSize: 13).bold let foreground = NSColor.green let attrString = NSAttributedString(string: previousTitle, attributes: [NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: foreground]) myPopUpButton.selectedItem?.attributedTitle = attrString
3条答案
按热度按时间zsohkypk1#
在网上搜索,我只找到了a really hacked, contorted answer to this question,可以更优雅地回答如下:
flmtquvp2#
我也有同样的问题。
为了保留原始文本属性,我的解决方案如下:
jhdbpxl93#
Swift 5.5
为菜单项分配属性字符串。例如,如果以前选择了该菜单项,则通过分配粗体绿色属性字符串来更改标题颜色。
我有一个属性,我为以前选择的标题,所以我可以很容易地删除属性字符串,如果另一个标题被选中。
然后在我的方法中,我做以下事情