我会用这个:
我建议sort
您在 NSTableView 委托中使用您的数据,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
}