wigging
wigging

Reputation: 9170

Change text color of the active and non-active NSTextField

I would like to change the text color to "red" when the NSTextField becomes active. All non-active text fields need to have "black" text.

Using the becomeFirstResponder method, I am able to change the text color to "red". However, when the text field looses focus, the text color remains "red". I need to the text color to change back to "black" once it is the non-active NSTextField. I tried the resignFirstResponder method but it doesn't change the text color back to "black".

Here's my code:

#import <Foundation/Foundation.h>

@interface MyTextField : NSTextField {
}

@end

and

#import "MyTextField.h"

@implementation MyTextField

- (BOOL)becomeFirstResponder {
    if (![super becomeFirstResponder]) {
        return NO;
    } else {
        [self setTextColor:[NSColor redColor]];
        return YES;
    }
}

- (BOOL)resignFirstResponder {
    if (![super resignFirstResponder]) {
        return NO;
    } else {
        [self setTextColor:[NSColor blackColor]];
        return YES;
    }
}

@end

Upvotes: 2

Views: 4635

Answers (2)

MatterGoal
MatterGoal

Reputation: 16430

Why you don't just add the method -textDidEndEditing in your NSTextField Subclass?

- (void)textDidEndEditing:(NSNotification *)notification
{
    [self setTextColor:[NSColor blackColor]];
    [super textDidEndEditing:notification];
}

Upvotes: 2

Francis McGrew
Francis McGrew

Reputation: 7272

I believe the problem is that the field editor is taking the color attribute when the text field becomes first responder but it replaces it when the text field resigns. You'll most likely want to change the attributes on the field editor directly.

You can do this by substituting your own field editor in the window's delegate like so:

- (id)windowWillReturnFieldEditor:(NSWindow *)sender toObject:(id)client {

    if ([client isKindOfClass:[MyTextField class]]) {

        static NSTextView *fieldEditor;

        if (nil == fieldEditor) {
            fieldEditor = [[NSTextView alloc] init];
            [fieldEditor setFieldEditor:YES];      
        }

        [fieldEditor setDelegate:client]; 
        [fieldEditor setTextColor:[NSColor redColor]];

        return fieldEditor;

    }
    else return nil;
}

Upvotes: 2

Related Questions