入力文字列の最初の文字を色付けしたい。controlDidChangeデリゲートメソッドで簡単にできます。しかし、次を使用してフォーマッタを追加した後:
[field setFormatter:[[MyFormatter alloc] init]];
NSTextField は、それに割り当てられた属性付きの文字列を無視します。
Appleのドキュメントを閲覧すると、
- (NSAttributedString *)attributedStringForObjectValue:(id)anObjects withDefaultAttributes:(NSDictionary *)aDict
メソッドですが、このメソッドは呼び出されません:(
AppDelegate.h
@interface AppDelegate : NSObject <NSApplicationDelegate, NSTextFieldDelegate>
{
IBOutlet NSTextField *field;
}
@property (assign) IBOutlet NSWindow *window;
@end
AppDelegate.m
#import "AppDelegate.h"
#import "MyFormatter.h"
@implementation AppDelegate
@synthesize window = _window;
- (void)dealloc
{
[super dealloc];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
[field setAttributedStringValue:[[NSAttributedString alloc] initWithString:@""]];
[field setAllowsEditingTextAttributes:YES];
[field setDelegate:self];
[field setFormatter:[[MyFormatter alloc] init]];
}
- (void)controlTextDidChange:(NSNotification *)obj
{
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:[field stringValue]];
[string addAttribute:NSForegroundColorAttributeName value:[NSColor redColor] range:NSMakeRange(0,1)];
[field setAttributedStringValue:string];
}
@end
MyFormatter.h
#import <Foundation/Foundation.h>
@interface MyFormatter : NSFormatter
- (NSAttributedString *)attributedStringForObjectValue:(id)anObjects withDefaultAttributes:(NSDictionary *)aDict;
@end
MyFormatter.m
#import "MyFormatter.h"
@implementation MyFormatter
- (NSString *)stringForObjectValue:(id)obj
{
return [(NSAttributedString *)obj string];
}
- (BOOL)getObjectValue:(id *)anObject forString:(NSString *)string errorDescription:(NSString **)error
{
*anObject = [[[NSMutableAttributedString alloc] initWithString:string] autorelease];
return YES;
}
- (NSAttributedString *)attributedStringForObjectValue:(id)anObjects withDefaultAttributes:(NSDictionary *)aDict
{
NSLog(@"This method is never called :(");
return nil;
}
@end