尝试更改 NSTextField 的选定文本背景颜色(我们有一个深色 UI,并且选定的文本背景与文本本身几乎相同),但似乎只有 NSTextView 允许我们更改它。
所以我们正在尝试使用 NSTextView 伪造 NSTextField,但无法让文本滚动工作相同。
我们得到的最接近的是这段代码:
NSTextView *tf = [ [ NSTextView alloc ] initWithFrame: NSMakeRect( 30.0, 20.0, 80.0, 22.0 ) ];
// Dark UI
[tf setTextColor:[NSColor whiteColor]];
[tf setBackgroundColor:[NSColor darkGrayColor]];
// Fixed size
[tf setVerticallyResizable:FALSE];
[tf setHorizontallyResizable:FALSE];
[tf setAlignment:NSRightTextAlignment]; // Make it right-aligned (yup, we need this too)
[[tf textContainer] setContainerSize:NSMakeSize(2000, 20)]; // Try to Avoid line wrapping with this ugly hack
[tf setFieldEditor:TRUE]; // Make Return key accept the textfield
// Set text properties
NSMutableDictionary *dict = [[[tf selectedTextAttributes] mutableCopy ] autorelease];
[dict setObject:[NSColor orangeColor] forKey:NSBackgroundColorAttributeName];
[tf setSelectedTextAttributes:dict];
这几乎可以正常工作,除了如果文本比文本字段长,您不能以任何方式滚动到它。
任何想法如何做到这一点?
提前致谢
感谢 Joshua,这是我正在寻找的一个很好的解决方案:
@interface ColoredTextField : NSTextField
- (BOOL)becomeFirstResponder;
@end
@implementation ColoredTextField
- (BOOL)becomeFirstResponder
{
if (![super becomeFirstResponder])
return NO;
NSDictionary * attributes = [NSDictionary dictionaryWithObjectsAndKeys :
[NSColor orangeColor], NSBackgroundColorAttributeName, nil];
NSTextView * fieldEditor = (NSTextView *)[[self window] fieldEditor:YES forObject:self];
[fieldEditor setSelectedTextAttributes:attributes];
return YES;
}
@end
与其用 NSTextView 伪造它,不如说它只是一个 NSTextField,当它成为第一响应者时,它会改变选定的文本颜色。
编辑:在文本字段中按 Enter 后,上面的代码将恢复为默认选择颜色。这是避免这种情况的一种方法。
@interface ColoredTextField : NSTextField
- (BOOL)becomeFirstResponder;
- (void)textDidEndEditing:(NSNotification *)notification;
- (void)setSelectedColor;
@end
@implementation ColoredTextField
- (BOOL)becomeFirstResponder
{
if (![super becomeFirstResponder])
return NO;
[self setSelectedColor];
return YES;
}
- (void)textDidEndEditing:(NSNotification *)notification
{
[super textDidEndEditing:notification];
[self setSelectedColor];
}
- (void) setSelectedColor
{
NSDictionary * attributes = [NSDictionary dictionaryWithObjectsAndKeys :
[NSColor orangeColor], NSBackgroundColorAttributeName, nil];
NSTextView * fieldEditor = (NSTextView *)[[self window] fieldEditor:YES forObject:self];
[fieldEditor setSelectedTextAttributes:attributes];
}
@end