In a view-based NSTableView, how make a control th

2019-04-07 10:14发布

问题:

View-based NSTableViews seem to have just the standard behavior, where, in order to make a text field inside the table the first responder, the user has to either double click or to single click and "keep calm".

However, given the flexibility view-based NSTableViews offer, this behavior is not not always desirable since there are now much different and complex applications possible than just doing an "old school" table.

How can I easily make a control (possibly in a cell together with other controls) inside a view-based NSTableView the first responder by a single click?

回答1:

To solve this, override this method on NSTableView:

@interface NSResponder (NSControlEditingSupport)

/* This is a responder chain method to allow controls to determine when they should become first responder or not. Some controls, such as NSTextField, should only become first responder when the enclosing NSTableView/NSBrowser indicates that the view can begin editing. It is up to the particular control that wants to be validated to call this method in its -mouseDown: (or other time) to determine if it should attempt to become the first responder or not. The default implementation returns YES when there is no -nextResponder, otherwise, it is forwarded up the responder chain. NSTableView/NSBrowser implements this to only allow first responder status if the responder is a view in a selected row. It also delays the first responder assignment if a doubleAction needs to (possibly) be sent. 'event' may be nil if there is no applicable event.
*/
- (BOOL)validateProposedFirstResponder:(NSResponder *)responder forEvent:(NSEvent *)event NS_AVAILABLE_MAC(10_7);

@end

And return YES right away to allow the firstResponder to be made quickly. The table "delays" making the first responder if a text field was hit, and doesn't allow it to be made unless the row was selected first.