Obj-C: Why is my NSTextField subclass having an ef

2019-02-20 14:34发布

问题:

I have an NSPanel with about 4 different NSTextField's on it. I'm looking at getting the usual cut, copy, paste, selectAll working for some of the fields.

The best solution I've found appears to be here: http://web.archive.org/web/20100126000339/http://www.cocoarocket.com/articles/copypaste.html

The AXCVHandler becomes a subclass of NSTextField. On my NSPanel in interface builder if I change a single NSTextField's class to be AXCVHandler, as shown in the link above, then the expected behavior to me would be that only that single text field would allow for cut, copy, and paste. The 3 remaining fields would not since they are still assigned the NSTextField class.

What I'm seeing though is the opposite of my expected behavior. I set a single NSTextField to the AXCVHandler and all of a sudden every single NSTextField on my NSPanel is working with cut, copy, paste ?!

Why is this? The 3 remaining text fields are assigned the NSTextField class yet they are calling performKeyEquivalent in my subclass ?!

What am I missing? Is this a mis-understanding of how firstResponder works or something else?

回答1:

From the article you linked to:

One interesting thing about this solution is that the handler object does not need to be the target view for actions. You could make a single NSButton perform the copy and paste operations for your whole window, if you'd like. (This is similar to the way that a single menu item can perform copy or paste operations for your whole application.)

The search for a view which wants to handle a key equivalent does not care which view is first responder. It searches the entire view hierarchy. Once it finds the single AXCVHandler, that object performs the key equivalent. The way it performs it is to send a corresponding action to the responder chain, which does begin at the first responder. So, that one AXCVHandler object is sufficient to direct the appropriate action to any of your text fields because any of them can be the first responder.