2011-12-27 17 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,格式化程序会将其转换为属性字符串。