NSPopUpButton白色文字

时间:2015-05-30 16:46:16

标签: macos swift custom-view nspopupbutton nspopupbuttoncell

我在自定义视图中的应用中创建了NSPopUpButton,其中包含黑色填充。我现在想让NSPopUpButton有一个白色文字颜色,但我似乎无法做到这一点。我应该怎么做呢?

由于

2 个答案:

答案 0 :(得分:2)

那很容易。您只需要重写-[NSPopUpButtonCell drawTitle:withFrame:inView],然后可以更改标题的所有内容,如颜色,字体,框架等。这是下面的示例。希望能对您有所帮助。

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

迅速:

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)
        }
    }
}

答案 1 :(得分:0)

使用-[NSButton setAttributedTitle:],请注意NSPopUpButtonNSButton的子类。制作属性标题的可变副本,将其前景色设置为白色,然后将其设置为新的属性标题。

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