2011-12-27 16 views
2

我想着色輸入字符串中的第一個字符。它可以通過controlDidChange委託方法輕鬆完成。但是,使用添加格式化後:如何使用NSFormatter爲NSTextField輸入顏色?

[field setFormatter:[[MyFormatter alloc] init]]; 

的NSTextField忽略分配給它的任何原因的字符串。

通過蘋果瀏覽的文檔給我的

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

你可以仔細檢查MyFormatter的代碼嗎?具體來說,'-stringForObjectValue:'看起來不正確。 – sbooth 2011-12-27 13:15:41

+0

@sbooth似乎沒問題:( – flagman 2011-12-27 17:16:48

回答

0

這不是它的工作原理。您必須設置objectValue,格式化程序會將其轉換爲屬性字符串。