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];
}
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.
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.
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.
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.
What's wrong with -[NSWindow firstResponder]
, which returns the first responder directly?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With