10

I would like to find the first responder view in a window. To do this, I would like to implement a category like this:

    @implementation  NSView (ViewExtensions)
- (NSView *)findFirstResponder
{
    if ([self isFirstResponder]) {        
        return self;     
    }

    for (NSView *subView in [self subviews]) {
        NSView *firstResponder = [subView findFirstResponder];

        if (firstResponder != nil) {
            return firstResponder;
        }
    }

    return nil;
}

@end

The above code is based on this question/answer on SO: Get the current first responder without using a private API.

The problem, perhaps, is that NSResponder doesn't have an isFirstResponder method like UIResponder does. What is the equivalent for NSResponder?

If the method above is implemented as above, I of course get the debug message: "'NSView' may not respond to 'isFirstResponder'".

How do I make findFirstResponder work in Cocoa?

Further information: I would later like to use the above method in my window controller in some way like:

        NSArray *copiedObjects;
        if ([[self window]contentView] == MyTableView) {
            copiedObjects = [tableController selectedObjects];
        }
        if ([[self window]contentView] == MyOutlineView) {
            copiedObjects = [treeController selectedFolders];
        }
Community
  • 1
  • 1
A A
  • 147
  • 1
  • 2
  • 8

2 Answers2

35

What's wrong with -[NSWindow firstResponder], which returns the first responder directly?

Ken Thomases
  • 88,520
  • 7
  • 116
  • 154
  • `-[NSWindow firstResponder]` returns an NSResponder. How do I get the NSView that is the first responder? Then I could do `if (firsResponderView == MyTableView)`, i.e. test whether a view is the current first responder? – A A Jun 10 '12 at 16:28
  • 10
    A view **is** a responder – `NSView` inherits from `NSResponder`. So, your `if` statement will just work. For the general case, you can do `if ([firstResponder isKindOfClass:[NSView class]]) { NSView* firstResponderView = (NSView*)firstResponder; /* do something with firstResponderView */ }`. – Ken Thomases Jun 10 '12 at 16:32
2

If you just want the first responder then use the firstResponder method of NSWindow.

You might want to use NSApplications targetForAction: method if you want the first responder for a particular action (like mouseDown:)

diederikh
  • 25,221
  • 5
  • 36
  • 49
  • I don't think that's what I'm after. I'd like to get "isFirstResponder" working in the category. I am not really looking for a response to a user click. I only mentioned that since, when the user clicks on an item in the table view, I assume it becomes the First Responder. All I want to do is find the First responder programmatically. I wonder how they did it here: http://stackoverflow.com/questions/1823317/how-do-i-legally-get-the-current-first-responder-on-the-screen-on-an-iphone – A A Jun 10 '12 at 14:41