I have created a NSPopUpButton
in my app in a custom view which has a black fill. I would now like to make the NSPopUpButton
have a white text color but I do not seem to be able to do this. How should I go about doing this?
Thanks
I have created a NSPopUpButton
in my app in a custom view which has a black fill. I would now like to make the NSPopUpButton
have a white text color but I do not seem to be able to do this. How should I go about doing this?
Thanks
That's easy. You just need to override the -[NSPopUpButtonCell drawTitle:withFrame:inView], and then can change everything about title, like color, font, frame , etc. Here is a example below. Hope that can help you.
Objective-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
Swift:
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)
}
}
}
Use
-[NSButton setAttributedTitle:]
, bearing in mind thatNSPopUpButton
is a subclass ofNSButton
. Make a mutable copy of the attributed title, set its foreground color to white, and then set that as the new attributed title.