Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Get Current First Responder from Window Controller in Cocoa?

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];
        }
like image 320
A A Avatar asked Jun 10 '12 13:06

A A


People also ask

What is the relationship between window and controller in Cocoa?

In Cocoa, a window is an instance of the NSWindow class, and the associated controller object is an instance of the NSWindowController class. In a well-designed app, you typically see a one-to-one relationship between a window and its controller.

What is a first responder in an app?

In an app, the responder object that first receives many kinds of events is known as the first responder. It receives key events, motion events, and action messages, among others.

How do I open a first responder in Visual Studio Code?

Open Main.storyboard. Go to the Application Scene and select File / Open menu item in the Main Menu. Then, switch to the Connections Inspector tab on the right sidebar. As you can see, it connects the menu action to the first responder via the openDocument: selector.

What is the responder chain for events in iOS?

However, the responder chain for events in iOS adds a variation to this path: If a view is managed by a view controller and if the view cannot handle an event, the view controller becomes the next responder. The path of an action message. For action messages, both OS X and iOS extend the responder chain to other objects.


1 Answers

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

like image 73
Ken Thomases Avatar answered Nov 06 '22 22:11

Ken Thomases