我想为输入字符串中的第一个字符着色。可以使用 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
我的格式化程序.h
#import <Foundation/Foundation.h>
@interface MyFormatter : NSFormatter
- (NSAttributedString *)attributedStringForObjectValue:(id)anObjects withDefaultAttributes:(NSDictionary *)aDict;
@end
我的格式化程序.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