2011-12-27 4 views
2

入力文字列の最初の文字を色付けしたいと思います。これは、controlDidChangeデリゲートメソッドで簡単に行うことができます。しかし、次のように使用してフォーマッタを追加した後:NSTextFieldは、割り当てられた属性付き文字列を無視します。アップルのドキュメントを閲覧NSFormatterを使用してNSTextFieldの入力を色付けする方法は?

AppDelegate.m

@interface AppDelegate : NSObject <NSApplicationDelegate, NSTextFieldDelegate> 
{ 
    IBOutlet NSTextField *field; 
} 
@property (assign) IBOutlet NSWindow *window;    
@end 

を私に

- (NSAttributedString *)attributedStringForObjectValue:(id)anObjects withDefaultAttributes:(NSDictionary *)aDict 

方法を与えたが、このメソッドが呼び出されることはありません:(

AppDelegate.h

#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 
+0

MyFormatterにコードを再確認できますか?特に '-stringForObjectValue:'は正しく表示されません。 – sbooth

+0

@sbooth okと思われる:( – flagman

答えて

0

これは、それがどのように動作するかではありません。 objectValueを設定する必要があり、フォーマッタはそれを属性付き文字列に変換します。

関連する問題