Arrow keys with NSTableView

后端 未结 4 1060
闹比i
闹比i 2020-12-08 16:50

Is it possible to navigate an NSTableView\'s editable cell around the NSTableView using arrow keys and enter/tab? For example, I want to make it feel more like a spreadsheet

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 17:37

    In Sequel Pro we used a different (and in my eyes simpler) method: We implemented control:textView:doCommandBySelector: in the delegate of the TableView. This method is hard to find -- it can be found in the NSControlTextEditingDelegate Protocol Reference. (Remember that NSTableView is a subclass of NSControl)

    Long story short, here's what we came up with (we didn't override left/right arrow keys, as those are used to navigate within the cell. We use Tab to go left/right)

    Please note that this is just a snippet from the Sequel Pro source code, and does not work as is

    - (BOOL)control:(NSControl *)control textView:(NSTextView *)textView doCommandBySelector:(SEL)command
    {
        NSUInteger row, column;
    
        row = [tableView editedRow];
        column = [tableView editedColumn];
    
        // Trap down arrow key
        if (  [textView methodForSelector:command] == [textView methodForSelector:@selector(moveDown:)] )
        {
            NSUInteger newRow = row+1;
            if (newRow>=numRows) return TRUE; //check if we're already at the end of the list
            if (column>= numColumns) return TRUE; //the column count could change
    
            [tableContentView selectRowIndexes:[NSIndexSet indexSetWithIndex:newRow] byExtendingSelection:NO];
            [tableContentView editColumn:column row:newRow withEvent:nil select:YES];
            return TRUE;
        }
    
        // Trap up arrow key
        else if (  [textView methodForSelector:command] == [textView methodForSelector:@selector(moveUp:)] )
        {
            if (row==0) return TRUE; //already at the beginning of the list
            NSUInteger newRow = row-1;
    
            if (newRow>=numRows) return TRUE;
            if (column>= numColumns) return TRUE;
    
            [tableContentView selectRowIndexes:[NSIndexSet indexSetWithIndex:newRow] byExtendingSelection:NO];
            [tableContentView editColumn:column row:newRow withEvent:nil select:YES];
            return TRUE;
        }
    

提交回复
热议问题