Re: How to set focus on editable table view cell on Enter key press

Christiaan Hofman <[email protected]> Wed, 5 Jan 2011 11:31:06 +0100
Newsgroups gmane.comp.macosx.devel
Message-ID <[email protected]>
On Jan 5, 2011, at 8:35, Abhijeet Singh wrote:

> Hi,I have a table view in my application. Table view has 3 columns. Items (rows) in table view are added on Enter (return) key press on keyboard. Column no 2 is editable and user needs to fill it. What I want to achieve is when user press Enter key on key board:1. New row is added in table view with column 1 & 3 filled (by default)2. Column 2 cell should be in edit mode and ready to accept the user input I have done the first step (1) but i am not able to set the focus on column2 cell and make it editable on Enter key press.

Use -selectRowIndexes:byExtendingSelection: and -editColumn:row:withEvent:select:.

> One more thing that i want to do is on Delete key press on keyboard the selected row in table view should be deleted. I can do it by putting a button on screen and connecting it with Delete key but i don't want to use a button on my screen.Any help will be appreciated.Thanks & RegardsAbhijeetGet Yourself a cool, short @in.com Email ID now!


For Delete, you need to implement -delete:, because that method is by default connected to the Delete key in the Edit menu. You implement that either in your window controller subclass, or in a tableview subclass, or both, depending on whether you want to have the delete key work everywhere or only when the tableview is focused. I have NSTableView subclasses that implement -delete: (and some other actions) going through custom delegate methods:

- (BOOL)canDelete {
    NSIndexSet *indexes = [self selectedRowIndexes];
    if ([indexes count] && [[self delegate] respondsToSelector:@selector(tableView:deleteRowsWithIndexes:)]) {
        if ([[self delegate] respondsToSelector:@selector(tableView:canDeleteRowsWithIndexes:)])
            return [[self delegate] tableView:self canDeleteRowsWithIndexes:indexes];
        else
            return YES;
    }
    return NO;
}

- (void)delete:(id)sender {
    if ([self canDelete])
        [[self delegate] tableView:self deleteRowsWithIndexes:[self selectedRowIndexes]];
    else
        NSBeep();
}

Christiaan