首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSPopUpButton白色文本

NSPopUpButton白色文本
EN

Stack Overflow用户
提问于 2015-05-31 00:46:16
回答 2查看 2.1K关注 0票数 3

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

谢谢

EN

回答 2

Stack Overflow用户

发布于 2019-10-02 08:38:05

这很简单。你只需要重写-NSPopUpButtonCell :withFrame:inView,然后就可以改变标题的所有内容,比如颜色、字体、边框等等。希望这能对你有所帮助。

Objective-C:

代码语言:javascript
复制
@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:

代码语言:javascript
复制
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)
        }
    }
}
票数 4
EN

Stack Overflow用户

发布于 2015-05-31 10:13:26

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

代码语言:javascript
复制
NSMutableAttributedString* myTitle = [[button.attributedTitle mutableCopy] autorelease];
NSRange allRange = NSMakeRange( 0, [myTitle length] );
myTitle addAttribute: NSForegroundColorAttributeName
    value: [NSColor whiteColor]
    range: allRange];
button.attributedTitle = myTitle;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30548730

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档