NSTableView - 通过单击另一行结束编辑后选择单击的行

时间:2012-07-07 22:20:22

标签: macos cocoa nstableview

我有一个NSTableView,无需绑定即可填充。

在数据源方法tableView:objectValueForTableColumn:row:中,我重新对数据进行排序,并在将编辑提交到模型后告诉表视图重新加载,以便在编辑后恢复正确的排序顺序。

但是,如果用户通过单击其他行结束编辑,并且由于刚刚结束的编辑而导致排序顺序发生更改,则可能会发生用户打算选择的行在单击它之后刚刚移动的行。因此,不是那一行,而是选择现在位于该点的另一行。

我尝试了NSTableViewDelegate方法的各种组合,但找不到调整选择的解决方案,以便在编辑结束后重新排序时,刚搬走的行得到了选择。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:3)

我会用这个:

我建议您使用NSTableView委托sort代替setObjectValue:

objectValueForTableColumn:数据

并更改NSTableView委托selectionIndexesForProposedSelection:

中的选择

此解决方案管理单个选择,如果您想管理单个和多个选择,我会更改我的答案。 如果用户双击,则它不起作用,因为它将选择更改为第二次单击。

您需要这些变量:

int originalRowIndex;
NSUInteger newRowIndex;

我初始化此变量:originalRowIndex = -1;

- (void)tableView:(NSTableView *)aTable setObjectValue:(id)anObject forTableColumn:(NSTableColumn *)aColumn row:(int)rowIndex {
    id objectAtRow = [myMutableArray objectAtIndex:rowIndex];
    NSString *columnKey = [aColumn identifier];
    [objectAtRow setValue:anObject forKey:columnKey];


    originalRowIndex = rowIndex; // get the original index
    [myMutableArray sortUsingDescriptors:[aTable sortDescriptors]]; // re-sort the mutable array
    newRowIndex = [myMutableArray indexOfObjectIdenticalTo:objectAtRow]; // get the new index
    if (newRowIndex == originalRowIndex) originalRowIndex = -1; // same position
}
// not called on empty selection
- (NSIndexSet *)tableView:(NSTableView *)tableView selectionIndexesForProposedSelection:(NSIndexSet *)proposedSelectionIndexes {
    int oIndex = originalRowIndex;
    originalRowIndex = -1;
    if (oIndex > -1 && [proposedSelectionIndexes count] > 1) { // if oIndex = -1 or multi selection , do nothing
        int i = [proposedSelectionIndexes firstIndex]; 
        if (oIndex < newRowIndex) { 
            if (i > oIndex && i <= newRowIndex) return [NSIndexSet indexSetWithIndex:(i - 1)];//shift the row index
        } else {
            if (i < oIndex && i >= newRowIndex) return [NSIndexSet indexSetWithIndex:(i + 1)];//shift the row index
        } //else doesn't change the selection, this index is out of range (originalIndex...newIndex)
    }
    return proposedSelectionIndexes;// doesn't change the selection
}

答案 1 :(得分:2)

我总是这么做:在做一些需要恢复选择的事情之前,我记得当前的选择 - 不是通过行索引,而是通过我可以在我的数据中找到的东西。我经常有一个字典数组,所以我只记得字典指针。

在对tableview做我需要做的任何事情之后,我只是再次查看数据,寻找我的对象以找到新的索引......