2012년 9월 14일 금요일

NSButton 글자 색 바꾸기

How to change NSButton's text color

NSButton은 기본적으로 글자 색 바꾸는 기능이 없다.

Mac OS 자체의 Theme에 따라가고 뻘짓 하지 말라는 Apple의 Guideline인 것은 아닐까 추측된다.

하지만 현실세계에서는 전체 System의 일관된 겉보기 따위는 개나 줘버리고 App 내의 Button의 배경그림과 글자색을 다 바꾸라는 변태스러운 요구가 빈번하기 때문에 어쩔 수 없이 바꿔야 한다.

검색해보면 글자색 바꾸는 것 까지는 찾기 쉬운데 그것을 적용하면 xib에서 지정했던 가운데 정렬이 없어지는 문제가 있었다. (뭐 다른것도 없어지긴 하겠지만 일단 대부분의 Button에서 중요한 이것!)

그래서 요리조리 해보니 setAlignment를 또 따로 해줘야 하더라.

이대로 두면 눌렀을 때 글자색이 원하지 않은 색으로 나울 수 있으므로 그것을 또 따로 지정하려면 setAttributedAlternateTitle: 을 사용하면 된다.

이렇게 알아낸 방법들을 짬뽕하여 아래와 같은 Category를 만들었다.

<NSButton+TextColor.h>
#import <Foundation/Foundation.h>

@interface NSButton (TextColor)

- (void)setTextColor:(NSColor *)color;
- (void)setHighlightedTextColor:(NSColor *)color;
+ (void)button:(NSButton *)button setTextColor:(NSColor *)color;
+ (void)button:(NSButton *)button setHighlightedTextColor:(NSColor *)color;

@end

<NSButton+TextColor.m>
#import "NSButton+TextColor.h"

@implementation NSButton (TextColor)

- (void)setTextColor:(NSColor *)color
{
    [NSButton button:self setTextColor:color];
}

- (void)setHighlightedTextColor:(NSColor *)color
{
    [NSButton button:self setHighlightedTextColor:color];
}

+ (void)button:(NSButton *)button setTextColor:(NSColor *)color
{
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    [style setAlignment:button.alignment];
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                button.font, NSFontAttributeName,
                                color, NSForegroundColorAttributeName,
                                style, NSParagraphStyleAttributeName,
                                nil];
    NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:button.title
                                                                  attributes:attributes];
    [button setAttributedTitle:attrStr];
}

+ (void)button:(NSButton *)button setHighlightedTextColor:(NSColor *)color
{
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    [style setAlignment:button.alignment];
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                button.font, NSFontAttributeName,
                                color, NSForegroundColorAttributeName,
                                style, NSParagraphStyleAttributeName,
                                nil];
    NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:button.title
                                                                  attributes:attributes];
    [button setAttributedAlternateTitle:attrStr];
}

@end


난 글자색 하나 바꾸려 했을 뿐;;

댓글 없음:

댓글 쓰기