Macos NSPoupButton白色文本

Macos NSPoupButton白色文本,macos,swift,custom-view,nspopupbutton,nspopupbuttoncell,Macos,Swift,Custom View,Nspopupbutton,Nspopupbuttoncell,我在应用程序中的自定义视图中创建了一个带有黑色填充的nspoupbutton。我现在想使nspoupbutton具有白色文本颜色,但我似乎无法做到这一点。我该怎么做呢 感谢使用-[NSButton setattributeditle:,记住nspoupbutton是NSButton的一个子类。制作属性标题的可变副本,将其前景色设置为白色,然后将其设置为新的属性标题 NSMutableAttributedString* myTitle = [[button.attributedTitle muta

我在应用程序中的自定义视图中创建了一个带有黑色填充的
nspoupbutton
。我现在想使
nspoupbutton
具有白色文本颜色,但我似乎无法做到这一点。我该怎么做呢


感谢使用
-[NSButton setattributeditle:
,记住
nspoupbutton
NSButton
的一个子类。制作属性标题的可变副本,将其前景色设置为白色,然后将其设置为新的属性标题

NSMutableAttributedString* myTitle = [[button.attributedTitle mutableCopy] autorelease];
NSRange allRange = NSMakeRange( 0, [myTitle length] );
myTitle addAttribute: NSForegroundColorAttributeName
    value: [NSColor whiteColor]
    range: allRange];
button.attributedTitle = myTitle;

那很容易。您只需覆盖-[NSPopUpButtonCell drawTitle:withFrame:inView],然后就可以更改标题的所有内容,如颜色、字体、边框等。下面是一个示例。希望能对你有所帮助

目标C:

@interface MyPopUpButtonCell : NSPopUpButtonCell

@property (nonatomic, readwrite, copy) NSColor *textColor;

@end

@implementation MyPopUpButtonCell

- (NSRect)drawTitle:(NSAttributedString*)title withFrame:(NSRect)frame inView:(NSView*)controlView {
        NSRect newFrame = NSMakeRect(NSMinX(frame), NSMinY(frame)+2, NSWidth(frame), NSHeight(frame));
        if (self.textColor) {
            NSMutableAttributedString *newTitle = [[NSMutableAttributedString alloc] initWithAttributedString:title];
            NSRange range = NSMakeRange(0, newTitle.length);
            [newTitle addAttribute:NSForegroundColorAttributeName value:self.textColor range:range];
            return [super drawTitle:newTitle withFrame:newFrame inView:controlView];
        }else {
            return [super drawTitle:title withFrame:newFrame inView:controlView];
        }
    }

@end
斯威夫特:

class MyPopUpButtonCell: NSPopUpButtonCell {
   var textColor: NSColor? = nil

   override
   func drawTitle(_ title: NSAttributedString, withFrame frame: NSRect, in controlView: NSView) -> NSRect {
        if self.textColor != nil {
            let attrTitle = NSMutableAttributedString.init(attributedString: title)
            let range = NSMakeRange(0, attrTitle.length)
            attrTitle.addAttributes([NSAttributedString.Key.foregroundColor : self.textColor!], range: range)
            return super.drawTitle(attrTitle, withFrame: frame, in: controlView)
        }else {
            return super.drawTitle(title, withFrame: frame, in: controlView)
        }
    }
}

您指的是标题文本、弹出菜单中的文本,还是两者都指?仅指标题文本。是否应将其添加到
viewdiload
?谢谢,
viewDidLoad
awakeFromNib
,在绘制控件之前调用的任何内容。是否需要从弹出按钮单元格的弹出按钮创建一个
IBOutlet
?谢谢,你需要给按钮打个出口。这就是我在示例代码中编写
按钮时的假设。