如何使用NSFormatter在NSTextField中着色输入?

时间:2011-12-27 10:56:26

标签: macos cocoa nstextfield nsattributedstring nsformatter

我想为输入字符串中的第一个字符着色。使用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

1 个答案:

答案 0 :(得分:0)

这不是它的工作原理。您必须设置objectValue,格式化程序会将其转换为属性字符串。