2012-10-28 4 views
21

OSX 꽤 어두운 이미지가있는 NSButton이 있습니다. 불행하게도 속성 검사기를 사용하여 색상을 변경할 수 없습니다. 그림보기 큰 검은 색 단추, 텍스트는 입니다.NSButton 텍스트를 색칠하는 방법

enter image description here

텍스트 색상을 변경할 수있는 가능성에 대한 어떤 단서? NSButton 클래스를 살펴 보았지만 그렇게 할 방법이 없습니다. 나는 내가 흰 글꼴로 이미지를 만들 수 있다는 것을 알고 있지만 그것은 내가하고 싶은 것이 아니다. 스위스, 로널드 호프만 에서

인사말 ---

+1

스위프트 4 일'setAttributedTitle을 시도 얻을 어떻게? –

+0

아직 안 됨, 잠시 기다려주십시오 :) NSAttributedString에서 setColor가 동일하지 않습니다. –

+0

'- [NSMutableAttributedString addAttribute : NSForegroundColorAttributeName 값 : [NSColor colorWithSRGBRed : 1.0 초록색 : 0.0 파란색 : 0.0 알파 : 0.0] 범위 : NSMakeRange (0, string.length)], –

답변

38

여기에 두 개의 다른 솔루션입니다 : 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]; 
} 
+0

답변을 수정하고 코드를 읽을 수 있도록 형식을 지정하십시오 – kleopatra

+0

다른 사용자가 내 게시물을 더 쉽게 읽을 수 있도록이 방법을 사용하십시오 –

+0

어느 방법 이건간에 문제가 발생하지 않습니다. – jheld

7

Apple은 NSButton의 텍스트 색상을 Popover example의 일부로 설정하는 코드가 있습니다. 다음은

은 (이 게시물에 대한 약간 수정, 검증되지 않은) 예제의 핵심입니다 : fixAttributesInRange:에 대한 호출은 (AN AppKit의 확장) 중요한 것 같다

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]; 

참고,하지만 난 찾을 수 없습니다 설명서가 인 이유는입니다. NSButton에서 속성이 지정된 문자열을 사용할 때 우려할만한 점은 아이콘과 같은 버튼에 대해 이미지도 정의되어있는 경우 속성이 지정된 문자열이 큰 사각형을 차지하고 이미지를 버튼의 가장자리까지 밀어 넣는 것입니다. 마음 속에 떠오르는 무엇인가.

그렇지 않으면 자신의 drawRect:을 대신 작성하는 것이 가장 좋은 방법 인 것처럼 보입니다.이 질문에는이 질문의 범위를 벗어나는 많은 함정이 있습니다.

11

내 솔루션 :

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

} 

및 스위프트 4 : 여기

.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 

enter image description here

그리고는 스위프트 3 버전입니다.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) 
    } 
} 
+0

잉크를 사용하면이 솔루션에 둥근 모서리를 추가 할 수 있습니까? :) – Yatko

+0

@Yatko는 NSRectFill (dirtyRect)를 다음으로 바꾸십시오. let rect = NSMakeRect (0, 0, bounds.width, bounds.height) rectanglePath = NSBezierPath (roundedRect : rect, xRadius : 3, yRadius : 3) .fill() –

2

이의 NSButton에 카테고리를 추가하고 간단하게 당신이 원하는 색상을 설정하고, 기존의 속성을 preseve는 등


에게 왼쪽 정렬 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 
-2
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; 
+0

해결책을 설명하는 텍스트를 추가 할 수 있습니까? – Kmeixner

2

정말 간단한, 재사용 가능한 솔루션 :

[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]; 
} 
2

저는 FlatButton이라는 NSButton 하위 클래스를 만들었습니다.이 하위 클래스를 사용하면 요청하는 것처럼 인터페이스 빌더의 속성 검사기에서 텍스트 색상을 매우 쉽게 변경할 수 있습니다. 그것은 귀하의 문제에 대한 간단하고 광범위한 솔루션을 제공해야합니다.

또한 색상 및 모양과 같은 다른 관련 스타일 지정 속성을 제공합니다.

현재 위치를 확인할 수있는 것들 :`: https://github.com/OskarGroth/FlatButton

FlatButton for macOS

0

이것은 내가 그것을

@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 
관련 문제