Подтвердить что ты не робот

NSButton как цвет текста

на OSX У меня есть NSButton с довольно темным изображением и, к сожалению, невозможно изменить цвет с помощью инспектора атрибутов. См. Изображение большой черной кнопки, текст Перейти.

enter image description here

Любые подсказки для возможности изменить цвет текста? Я посмотрел на класс NSButton, но нет способа сделать это. Я знаю, что я мог бы сделать изображение с белым шрифтом, но это не то, что я хочу сделать.

Приветствия из Швейцарии, Рональд Хофманн ---

4b9b3361

Ответ 1

Вот два других решения: http://denis-druz.okis.ru/news.534557.Text-Color-in-NSButton.html

решение 1:

-(void)awakeFromNib
{
    NSColor *color = [NSColor greenColor];
    NSMutableAttributedString *colorTitle = [[NSMutableAttributedString alloc] initWithAttributedString:[button attributedTitle]];
    NSRange titleRange = NSMakeRange(0, [colorTitle length]);
    [colorTitle addAttribute:NSForegroundColorAttributeName value:color range:titleRange];
    [button setAttributedTitle:colorTitle];
}

решение 2:

в *.m файле:

- (void)setButtonTitleFor:(NSButton*)button toString:(NSString*)title withColor:(NSColor*)color
{
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    [style setAlignment:NSCenterTextAlignment];
    NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:color, NSForegroundColorAttributeName, style, NSParagraphStyleAttributeName, nil];
    NSAttributedString *attrString = [[NSAttributedString alloc]initWithString:title attributes:attrsDictionary];
    [button setAttributedTitle:attrString];
}

-(void)awakeFromNib
{
    NSString *title = @"+Add page";
    NSColor *color = [NSColor greenColor];
    [self setButtonTitleFor:button toString:title withColor:color];
}

Ответ 2

Мое решение:

.h

IB_DESIGNABLE
@interface DVButton : NSButton

@property (nonatomic, strong) IBInspectable NSColor *BGColor;
@property (nonatomic, strong) IBInspectable NSColor *TextColor;

@end


.m

@implementation DVButton

- (void)awakeFromNib
{
    if (self.TextColor)
    {
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        [style setAlignment:NSCenterTextAlignment];
        NSDictionary *attrsDictionary  = [NSDictionary dictionaryWithObjectsAndKeys:
                                          self.TextColor, NSForegroundColorAttributeName,
                                          self.font, NSFontAttributeName,
                                          style, NSParagraphStyleAttributeName, nil];
        NSAttributedString *attrString = [[NSAttributedString alloc]initWithString:self.title attributes:attrsDictionary];
        [self setAttributedTitle:attrString];
    }
}


- (void)drawRect:(NSRect)dirtyRect
{
    if (self.BGColor)
    {
        // add a background colour
        [self.BGColor setFill];
        NSRectFill(dirtyRect);
    }

    [super drawRect:dirtyRect];
}

@end

введите описание изображения здесь

И вот версия Swift 3:

import Cocoa

@IBDesignable
class DVButton: NSButton
{
    @IBInspectable var bgColor: NSColor?
    @IBInspectable var textColor: NSColor?

    override func awakeFromNib()
    {
        if let textColor = textColor, let font = font
        {
            let style = NSMutableParagraphStyle()
            style.alignment = .center

            let attributes =
            [
                NSForegroundColorAttributeName: textColor,
                NSFontAttributeName: font,
                NSParagraphStyleAttributeName: style
            ] as [String : Any]

            let attributedTitle = NSAttributedString(string: title, attributes: attributes)
            self.attributedTitle = attributedTitle
        }
    }

    override func draw(_ dirtyRect: NSRect)
    {
        if let bgColor = bgColor
        {
            bgColor.setFill()
            NSRectFill(dirtyRect)
        }

        super.draw(dirtyRect)
    }

}

и версия Swift 4.0:

import Cocoa

@IBDesignable
 class Button: NSButton
{
    @IBInspectable var bgColor: NSColor?
    @IBInspectable var textColor: NSColor?

    override func awakeFromNib()
    {
        if let textColor = textColor, let font = font
        {
            let style = NSMutableParagraphStyle()
            style.alignment = .center

            let attributes =
            [
                NSAttributedStringKey.foregroundColor: textColor,
                NSAttributedStringKey.font: font,
                NSAttributedStringKey.paragraphStyle: style
             ] as [NSAttributedStringKey : Any]

            let attributedTitle = NSAttributedString(string: title, attributes: attributes)
            self.attributedTitle = attributedTitle
        }
    }

    override func draw(_ dirtyRect: NSRect)
    {
        if let bgColor = bgColor
        {
            bgColor.setFill()
            __NSRectFill(dirtyRect)
        }

        super.draw(dirtyRect)
    }
}

Ответ 3

У Apple есть код для установки цвета текста NSButton как часть Пример Popover.

Ниже приведен пример примера (слегка измененный для этого сообщения, не проверенный):

NSButton *button = ...;
NSMutableAttributedString *attrTitle =
    [[NSMutableAttributedString alloc] initWithString:@"Make Me Red"];
NSUInteger len = [attrTitle length];
NSRange range = NSMakeRange(0, len);
[attrTitle addAttribute:NSForegroundColorAttributeName value:[NSColor redColor] range:range];
[attrTitle fixAttributesInRange:range];
[button setAttributedTitle:attrTitle];

Обратите внимание, что вызов fixAttributesInRange: кажется важным (расширение AppKit), но я не могу найти документацию о том, почему это так. Единственное беспокойство, которое я испытываю при использовании атрибутных строк в NSButton, - это то, что изображение также определено для кнопки (например, значок), атрибутная строка будет занимать большой прямоугольник и нажимать изображение на край кнопки. Что-то нужно иметь в виду.

В противном случае лучше всего сделать вместо этого свой собственный drawRect: переопределение, в котором есть много других ошибок, выходящих за рамки этого вопроса.

Ответ 4

Вот как я это делаю в Swift 4

 @IBOutlet weak var myButton: NSButton!

 // create the attributed string
 let myString = "My Button Title"
 let myAttribute = [ NSAttributedStringKey.foregroundColor: NSColor.blue ]
 let myAttrString = NSAttributedString(string: myString, attributes: myAttribute)
 // assign it to the button
 myButton.attributedTitle = myAttrString

Ответ 5

Я создал подкласс NSButton под названием FlatButton, что делает его очень простым в изменении цвета текста в инспекторе атрибутов интерфейса Builder, как вы просите. Он должен обеспечить простое и исчерпывающее решение вашей проблемы.

Он также предоставляет другие соответствующие атрибуты стиля, такие как цвет и форма.

Вы найдете его здесь: https://github.com/OskarGroth/FlatButton

FlatButton for macOS

Ответ 6

Добавьте категорию в NSButton и просто установите цвет в соответствии с тем, что вы хотите, и представьте существующие атрибуты, так как заголовок может быть центрирован, выравниваться влево и т.д.


@implementation NSButton (NSButton_IDDAppKit)

- (NSColor*)titleTextColor {

    return [NSColor redColor];

}

- (void)setTitleTextColor:(NSColor*)aColor {

    NSMutableAttributedString*  attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedTitle];
    NSString*  title = self.title;
    NSRange  range = NSMakeRange(0.0, self.title.length);

    [attributedString addAttribute:NSForegroundColorAttributeName value:aColor range:range];
    [self setAttributedTitle:attributedString];
    [attributedString release];

}

@end

Ответ 7

Очень простое, многоразовое решение без подкласса NSButton:

[self setButton:self.myButton fontColor:[NSColor whiteColor]] ;

-(void) setButton:(NSButton *)button fontColor:(NSColor *)color {
    NSMutableAttributedString *colorTitle = [[NSMutableAttributedString alloc] initWithAttributedString:[button attributedTitle]];
    [colorTitle addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0, button.attributedTitle.length)];
    [button setAttributedTitle:colorTitle];
}

Ответ 8

NSColor color = NSColor.White;  
NSMutableAttributedString colorTitle = new NSMutableAttributedString (cb.Cell.Title);                
NSRange titleRange = new NSRange (0, (nint)cb.Cell.Title.Length);
colorTitle.AddAttribute (NSStringAttributeKey.ForegroundColor, color, titleRange);      
cb.Cell.AttributedTitle = colorTitle;  

Ответ 9

Используя информацию выше, я написал расширение NSButton, которое устанавливает цвет переднего плана, а также системный шрифт и выравнивание текста.

Это для Cocoa на Swift 4.x, но может быть легко приспособлено для iOS.

import Cocoa

extension NSButton {
    func setAttributes(foreground: NSColor? = nil, fontSize: CGFloat = -1.0, alignment: NSTextAlignment? = nil) {

        var attributes: [NSAttributedStringKey: Any] = [:]

        if let foreground = foreground {
            attributes[NSAttributedStringKey.foregroundColor] = foreground
        }

        if fontSize != -1 {
            attributes[NSAttributedStringKey.font] = NSFont.systemFont(ofSize: fontSize)
        }

        if let alignment = alignment {
            let paragraph = NSMutableParagraphStyle()
            paragraph.alignment = alignment
            attributes[NSAttributedStringKey.paragraphStyle] = paragraph
        }

        let attributed = NSAttributedString(string: self.title, attributes: attributes)
        self.attributedTitle = attributed
    }
}

Ответ 10

Когда ваша цель MacOS 10,14 или более поздняя версия, вы можете использовать новый tintColor свойство управления NSButton установить цвет текста.

Ответ 11

Swift 4.2 версия решения Дэвида Бойда

extension NSButton {
func setAttributes(foreground: NSColor? = nil, fontSize: CGFloat = -1.0, alignment: NSTextAlignment? = nil) {

    var attributes: [NSAttributedString.Key: Any] = [:]

    if let foreground = foreground {
        attributes[NSAttributedString.Key.foregroundColor] = foreground
    }

    if fontSize != -1 {
        attributes[NSAttributedString.Key.font] = NSFont.systemFont(ofSize: fontSize)
    }

    if let alignment = alignment {
        let paragraph = NSMutableParagraphStyle()
        paragraph.alignment = alignment
        attributes[NSAttributedString.Key.paragraphStyle] = paragraph
    }

    let attributed = NSAttributedString(string: self.title, attributes: attributes)
    self.attributedTitle = attributed
}

}