gpt4 book ai didi

macos - 如何使用 NSFormatter 对 NSTextField 中的输入进行着色?

转载 作者:行者123 更新时间:2023-12-03 16:47:36 24 4
gpt4 key购买 nike

我想对输入字符串中的第一个字符进行着色。使用 controlDidChange 委托(delegate)方法可以轻松完成此操作。但是添加格式化程序后使用:

[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

最佳答案

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

关于macos - 如何使用 NSFormatter 对 NSTextField 中的输入进行着色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8643860/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com