如何在NSTableView中重新排序行?

时间:2015-10-30 11:01:41

标签: objective-c macos cocoa nstableview

我似乎无法找到一种快速简便的方法来简单地重新排序NSTableView(OSX,而​​不是iOS)中的行。在iOS上我会使用这两个委托方法:

// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
    MyObject *obj = [model objectAtIndex:fromIndexPath.row];
    [model removeObject:obj]; 
    [model insertObject:obj atIndex:toIndexPath.row];
}

有没有快速简便的方法为Cocoa中的NSTableView做类似的事情?到目前为止,我只使用粘贴板找到了一些广泛的代码示例,这看起来非常类似于对我来说简单的重新排序功能。

1 个答案:

答案 0 :(得分:7)

谢谢大家,这对我来说非常有用:

//add line somewhere in your code
#define MyPrivateTableViewDataType @"MyPrivateTableViewDataType"

//add line in your viewDidLoad: method
[self.tableView registerForDraggedTypes:[NSArray arrayWithObject:MyPrivateTableViewDataType]

这些数据源方法可以复制到代码中而不做任何改动:

// drag operation stuff
- (BOOL)tableView:(NSTableView *)tv writeRowsWithIndexes:(NSIndexSet *)rowIndexes toPasteboard:(NSPasteboard*)pboard {
    // Copy the row numbers to the pasteboard.
    NSData *zNSIndexSetData = [NSKeyedArchiver archivedDataWithRootObject:rowIndexes];

    [pboard declareTypes:[NSArray arrayWithObject:MyPrivateTableViewDataType] owner:self];

    [pboard setData:zNSIndexSetData forType:MyPrivateTableViewDataType];

    return YES;
}

- (NSDragOperation)tableView:(NSTableView*)tv validateDrop:(id )info proposedRow:(NSInteger)row proposedDropOperation:(NSTableViewDropOperation)op {
    // Add code here to validate the drop
    return NSDragOperationEvery;
}

这部分需要实现自定义模型,就像上面的问题一样:

- (BOOL)tableView:(NSTableView *)aTableView acceptDrop:(id )info row:(NSInteger)row dropOperation:(NSTableViewDropOperation)operation {

    NSPasteboard* pboard = [info draggingPasteboard];
    NSData* rowData = [pboard dataForType:MyPrivateTableViewDataType];
    NSIndexSet* rowIndexes = [NSKeyedUnarchiver unarchiveObjectWithData:rowData];
    NSInteger dragRow = [rowIndexes firstIndex];





    if (dragRow < row) {
        [model insertObject:[model objectAtIndex:dragRow] atIndex:row];
        [model removeObjectAtIndex:dragRow];

        [aTableView noteNumberOfRowsChanged];
        [aTableView moveRowAtIndex:dragRow toIndex:row-1];

    }else {
        ModelObj *obj = [model objectAtIndex:dragRow];
        [model removeObjectAtIndex:dragRow];
        [model insertObject:obj atIndex:row];

        [aTableView noteNumberOfRowsChanged];
        [aTableView moveRowAtIndex:dragRow toIndex:row];
    }

    return YES;
}