dhrm
dhrm

Reputation: 14934

How to resign focus on NSTextField when clicking outside

I've a NSView with a editable NSTextField and multiple other subviews like NSView, NSSlider, NSImage etc.

  1. After I've entered my text into the editable NSTextField and click on any of the other views, move the slider etc. I would like my NSTextField to lose focus. I've tried calling the resignFirstResponder, but that does not seems to work. How can I do this?
  2. When I mark the text inside my NSTextField a blue background behind the text is shown. How can I change the color is this?

Upvotes: 5

Views: 5201

Answers (3)

Hussain Shabbir
Hussain Shabbir

Reputation: 15015

Try the following method:

 [[NSApp mainWindow] performSelector:@selector(resignFirstResponder:)
                          withObject:yourTextfield
                          afterDelay:0.0];

Upvotes: 0

JWWalker
JWWalker

Reputation: 22707

For question 1, I agree with BlueTomato that you need to make something else first responder, not call resignFirstResponder. For question 2, subclass NSTextFieldCell, and in the subclass, have an override like this:

- (NSText *)setUpFieldEditorAttributes:(NSText *)textObj
{
    [super setUpFieldEditorAttributes: textObj];

    if ([textObj isKindOfClass: [NSTextView class]])
    {
        NSTextView* textView = (NSTextView*) textObj;

        [textView setSelectedTextAttributes:
            [NSDictionary dictionaryWithObjectsAndKeys:
                [NSColor redColor],
                NSBackgroundColorAttributeName,
                nil] ];
    }

    return textObj;
}

Upvotes: 3

El Tomato
El Tomato

Reputation: 6707

Suppose that you have a subclass of NSView called clickView1.h. In reference to this post, you can achieve your goal in No. 1 as follows.

- (void)mouseDown:(NSEvent *)event{
    AppDelegate *appDelegate = (AppDelegate *)[NSApp delegate];
    [appDelegate.window makeFirstResponder:nil];
}

As for No. 2, I don't understand the question.

Upvotes: 9

Related Questions