Is it possible to make my NSTableView accept a deleteevnt (backspace og even c开发者_Go百科md+backspace) ? I have an NSMenu where i have my delete-menu-item connected to my first responder object in the nib.
Any pointers?
One approach which is easy to implement:
- add +/- buttons to your interface in IB and connect them to a deleteRecord IBAction
- with the delete (-) button selected in IB, navigate to Attributes Inspector > Button > Key Equivalent
- click in the box to start recording your keypress, then hit the Delete/Backspace key
When you build your project, given that you implement the deleteRecord method, a Backspace keypress will delete records from your tableview
This is a modern solution using NSViewController
and First Responder
.
The Delete
menu item in the menu Edit
is connected to the selector delete:
of First Responder. If there is no Delete
menu item, create one and connect it to delete:
of First Responder (red cube).
- Assign a key equivalent to the
Delete
menu item (⌫ or ⌘⌫) In the view controller implement the
IBAction
methodSwift:
@IBAction func delete(_ sender: AnyObject)
Objective-C:
-(IBAction)delete:(id)sender
and put in the logic to delete the table view row(s).
No subclass needed.
The correct way of implementing this functionality is by using key-bindings:
- Select the delete menu item in IB and set it's key equivalent to the backspace key for example.
- Connect the menu items action to a method you wrote for handling the task. This method will be found for you automatically up the responder chain, when you connect it through the first responder.
- Implement your delete functionality.
Depending upon which kind of application you write, there are validation delegate methods. By which means you can set the menu items enabled state. For a document based application this validation happens through - (BOOL)validateUserInterfaceItem:(id)anItem
.
You could create a subclass of NSTableView, overriding keyDown
like so:
- (void)keyDown:(NSEvent *)theEvent
{
unichar key = [[theEvent charactersIgnoringModifiers] characterAtIndex:0];
if(key == NSDeleteCharacter)
{
[self deleteItem];
return;
}
[super keyDown:theEvent];
}
Then make sure that any NSTableView that you want to have the delete functionality uses your subclass in Interface Builder instead of the regular NSTableView.
You can implement the - (void)deleteItem
method for example like this:
- (void)deleteItem
{
if ([self numberOfSelectedRows] == 0) return;
NSUInteger index = [self selectedRow];
[documentController deleteItemWithIndex:index];
}
精彩评论